7 public function bound($abstract);
8 public function alias($abstract, $alias);
9 public function tag($abstracts, $tags);
11 public function bind($abstract, $concrete = null, $shared =
false);
12 public function bindIf($abstract, $concrete = null, $shared =
false);
13 public function singleton($abstract, $concrete = null);
15 public function instance($abstract, $instance);
16 public function when($concrete);
17 public function make($abstract, $parameters = array());
18 public function call($callback, array $parameters = array(), $defaultMethod = null);
27 public function needs($abstract);
28 public function give($implementation);
36 public function basePath();
37 public function environment();
38 public function isDownForMaintenance();
39 public function registerConfiguredProviders();
40 public function register($provider,
$options = array(), $force =
false);
41 public function registerDeferredProvider($provider, $service = null);
42 public function boot();
43 public function booting($callback);
44 public function booted($callback);
52 public function dispatchFromArray($command, array $array);
53 public function dispatchFrom($command,
ArrayAccess $source, array $extras = array());
55 public function dispatchNow($command,
Closure $afterResolving = null);
56 public function pipeThrough(array $pipes);
62 public function dispatchToQueue($command);
69 public function resolveHandler($command);
70 public function getHandlerClass($command);
71 public function getHandlerMethod($command);
72 public function maps(array $commands);
73 public function mapUsing(
Closure $mapper);
80 public function send($traveler);
81 public function through($stops);
82 public function via($method);
83 public function then(
Closure $destination);
95 public function alert($message, array $context = array());
96 public function critical($message, array $context = array());
97 public function error($message, array $context = array());
98 public function warning($message, array $context = array());
99 public function notice($message, array $context = array());
100 public function info($message, array $context = array());
101 public function debug($message, array $context = array());
102 public function log($level, $message, array $context = array());
103 public function useFiles(
$path, $level =
'debug');
104 public function useDailyFiles(
$path, $days = 0, $level =
'debug');
110 public function has($key);
111 public function get($key, $default = null);
112 public function set($key, $value = null);
113 public function prepend($key, $value);
114 public function push($key, $value);
120 public function listen($events, $listener, $priority = 0);
121 public function hasListeners($eventName);
122 public function until($event, $payload = array());
123 public function fire($event, $payload = array(), $halt =
false);
124 public function firing();
125 public function forget($event);
126 public function forgetPushed();
132 public function toArray();
138 public function toJson(
$options = 0);
144 public function make($name, $value, $minutes = 0,
$path = null, $domain = null, $secure =
false, $httpOnly =
true);
145 public function forever($name, $value,
$path = null, $domain = null, $secure =
false, $httpOnly =
true);
146 public function forget($name,
$path = null, $domain = null);
152 public function queue();
153 public function unqueue($name);
154 public function getQueuedCookies();
160 public function encrypt($value);
161 public function decrypt($payload);
162 public function setMode($mode);
163 public function setCipher($cipher);
169 public function getQueueableId();
176 public function get(
$uri, $action);
177 public function post(
$uri, $action);
178 public function put(
$uri, $action);
179 public function delete(
$uri, $action);
180 public function patch(
$uri, $action);
182 public function match($methods,
$uri, $action);
183 public function resource($name, $controller, array
$options = array());
184 public function group(array $attributes,
Closure $callback);
185 public function before($callback);
186 public function after($callback);
187 public function filter($name, $callback);
193 public function make($content =
'', $status = 200, array $headers = array());
194 public function view($view, $data = array(), $status = 200, array $headers = array());
195 public function json($data = array(), $status = 200, array $headers = array(),
$options = 0);
196 public function jsonp($callback, $data = array(), $status = 200, array $headers = array(),
$options = 0);
197 public function stream($callback, $status = 200, array $headers = array());
198 public function download($file, $name = null, array $headers = array(), $disposition =
'attachment');
199 public function redirectTo(
$path, $status = 302, $headers = array(), $secure = null);
200 public function redirectToRoute($route, $parameters = array(), $status = 302, $headers = array());
201 public function redirectToAction($action, $parameters = array(), $status = 302, $headers = array());
202 public function redirectGuest(
$path, $status = 302, $headers = array(), $secure = null);
203 public function redirectToIntended($default =
'/', $status = 302, $headers = array(), $secure = null);
209 public function to(
$path, $extra = array(), $secure = null);
210 public function secure(
$path, $parameters = array());
211 public function asset(
$path, $secure = null);
212 public function route($name, $parameters = array(), $absolute =
true);
213 public function action($action, $parameters = array(), $absolute =
true);
214 public function setRootControllerNamespace($rootNamespace);
220 public function getRouteKey();
221 public function getRouteKeyName();
228 public function handle($request,
Closure $next);
234 public function terminate($request,
$response);
240 public function validate();
246 public function exists($view);
247 public function file(
$path, $data = array(), $mergeData = array());
248 public function make($view, $data = array(), $mergeData = array());
249 public function share($key, $value = null);
250 public function composer($views, $callback, $priority = null);
251 public function creator($views, $callback);
252 public function addNamespace($namespace, $hints);
258 public function getMessageBag();
264 public function keys();
265 public function add($key, $message);
266 public function merge($messages);
267 public function has($key = null);
268 public function first($key = null, $format = null);
269 public function get($key, $format = null);
270 public function all($format = null);
271 public function getFormat();
272 public function setFormat($format =
':message');
274 public function count();
275 public function toArray();
282 public function name();
283 public function with($key, $value = null);
289 public function bootstrap();
290 public function handle($request);
291 public function terminate($request,
$response);
292 public function getApplication();
298 public function check();
299 public function guest();
300 public function user();
301 public function once(array $credentials = array());
302 public function attempt(array $credentials = array(), $remember =
false, $login =
true);
303 public function basic($field =
'email');
304 public function onceBasic($field =
'email');
305 public function validate(array $credentials = array());
307 public function loginUsingId($id, $remember =
false);
308 public function viaRemember();
309 public function logout();
315 public function make($value, array
$options = array());
316 public function check($value, $hashedValue, array
$options = array());
317 public function needsRehash($hashedValue, array
$options = array());
326 $guard = parent::createDriver($driver);
327 $guard->setCookieJar($this->app[
'cookie']);
328 $guard->setDispatcher($this->app[
'events']);
329 return $guard->setRequest($this->app->refresh(
'request', $guard,
'setRequest'));
333 $custom = parent::callCustomCreator($driver);
334 if ($custom instanceof
Guard) {
337 return new Guard($custom, $this->app[
'session.store']);
341 $provider = $this->createDatabaseProvider();
342 return new Guard($provider, $this->app[
'session.store']);
346 $connection = $this->app[
'db']->connection();
347 $table = $this->app[
'config'][
'auth.table'];
352 $provider = $this->createEloquentProvider();
353 return new Guard($provider, $this->app[
'session.store']);
357 $model = $this->app[
'config'][
'auth.model'];
362 return $this->app[
'config'][
'auth.driver'];
366 $this->app[
'config'][
'auth.driver'] = $name;
384 protected $viaRemember =
false;
390 protected $loggedOut =
false;
391 protected $tokenRetrievalAttempted =
false;
395 $this->request = $request;
396 $this->provider = $provider;
400 return !is_null($this->user());
404 return !$this->check();
408 if ($this->loggedOut) {
411 if (!is_null($this->user)) {
414 $id = $this->
session->get($this->getName());
417 $user = $this->provider->retrieveById($id);
419 $recaller = $this->getRecaller();
420 if (is_null($user) && !is_null($recaller)) {
421 $user = $this->getUserByRecaller($recaller);
423 $this->updateSession($user->getAuthIdentifier());
424 $this->fireLoginEvent($user,
true);
427 return $this->user = $user;
431 if ($this->loggedOut) {
434 $id = $this->
session->get($this->getName(), $this->getRecallerId());
435 if (is_null($id) && $this->user()) {
436 $id = $this->user()->getAuthIdentifier();
442 if ($this->validRecaller($recaller) && !$this->tokenRetrievalAttempted) {
443 $this->tokenRetrievalAttempted =
true;
444 list($id, $token) = explode(
'|', $recaller, 2);
445 $this->viaRemember = !is_null($user = $this->provider->retrieveByToken($id, $token));
451 return $this->request->cookies->get($this->getRecallerName());
455 if ($this->validRecaller($recaller = $this->getRecaller())) {
456 return head(explode(
'|', $recaller));
461 if (!is_string($recaller) || !str_contains($recaller,
'|')) {
464 $segments = explode(
'|', $recaller);
465 return count($segments) == 2 && trim($segments[0]) !==
'' && trim($segments[1]) !==
'';
467 public function once(array $credentials = array())
469 if ($this->validate($credentials)) {
470 $this->setUser($this->lastAttempted);
475 public function validate(array $credentials = array())
477 return $this->attempt($credentials,
false,
false);
479 public function basic($field =
'email')
481 if ($this->check()) {
484 if ($this->attemptBasic($this->getRequest(), $field)) {
487 return $this->getBasicResponse();
491 if (!$this->
once($this->getBasicCredentials($this->getRequest(), $field))) {
492 return $this->getBasicResponse();
500 return $this->attempt($this->getBasicCredentials($request, $field));
508 $headers = array(
'WWW-Authenticate' =>
'Basic');
509 return new Response(
'Invalid credentials.', 401, $headers);
511 public function attempt(array $credentials = array(), $remember =
false, $login =
true)
513 $this->fireAttemptEvent($credentials, $remember, $login);
514 $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);
515 if ($this->hasValidCredentials($user, $credentials)) {
517 $this->login($user, $remember);
525 return !is_null($user) && $this->provider->validateCredentials($user, $credentials);
530 $payload = array($credentials, $remember, $login);
531 $this->events->fire(
'auth.attempt', $payload);
537 $this->events->listen(
'auth.attempt', $callback);
540 public function login(UserContract $user, $remember =
false)
542 $this->updateSession($user->getAuthIdentifier());
544 $this->createRememberTokenIfDoesntExist($user);
545 $this->queueRecallerCookie($user);
547 $this->fireLoginEvent($user, $remember);
548 $this->setUser($user);
552 if (isset($this->events)) {
553 $this->events->fire(
'auth.login', array($user, $remember));
558 $this->
session->set($this->getName(), $id);
563 $this->
session->set($this->getName(), $id);
564 $this->login($user = $this->provider->retrieveById($id), $remember);
569 $this->setUser($this->provider->retrieveById($id));
570 return $this->user instanceof UserContract;
574 $value = $user->getAuthIdentifier() .
'|' . $user->getRememberToken();
575 $this->getCookieJar()->queue($this->createRecaller($value));
579 return $this->getCookieJar()->forever($this->getRecallerName(), $value);
583 $user = $this->user();
584 $this->clearUserDataFromStorage();
585 if (!is_null($this->user)) {
586 $this->refreshRememberToken($user);
588 if (isset($this->events)) {
589 $this->events->fire(
'auth.logout', array($user));
592 $this->loggedOut =
true;
596 $this->
session->remove($this->getName());
597 $recaller = $this->getRecallerName();
598 $this->getCookieJar()->queue($this->getCookieJar()->forget($recaller));
602 $user->setRememberToken($token = str_random(60));
603 $this->provider->updateRememberToken($user, $token);
607 $rememberToken = $user->getRememberToken();
608 if (
empty($rememberToken)) {
609 $this->refreshRememberToken($user);
614 if (!isset($this->cookie)) {
617 return $this->cookie;
621 $this->cookie = $cookie;
625 return $this->events;
629 $this->events = $events;
633 return $this->session;
637 return $this->provider;
641 $this->provider = $provider;
650 $this->loggedOut =
false;
658 $this->request = $request;
663 return $this->lastAttempted;
667 return 'login_' . md5(get_class($this));
671 return 'remember_' . md5(get_class($this));
675 return $this->viaRemember;
682 public function retrieveById($identifier);
683 public function retrieveByToken($identifier, $token);
685 public function retrieveByCredentials(array $credentials);
686 public function validateCredentials(
Authenticatable $user, array $credentials);
699 $this->model = $model;
700 $this->hasher = $hasher;
704 return $this->createModel()->newQuery()->find($identifier);
708 $model = $this->createModel();
709 return $model->newQuery()->where($model->getKeyName(), $identifier)->where($model->getRememberTokenName(), $token)->first();
713 $user->setRememberToken($token);
718 $query = $this->createModel()->newQuery();
719 foreach ($credentials as $key => $value) {
720 if (!str_contains($key,
'password')) {
721 $query->where($key, $value);
724 return $query->first();
728 $plain = $credentials[
'password'];
729 return $this->hasher->check($plain, $user->getAuthPassword());
733 $class =
'\\' . ltrim($this->model,
'\\');
747 class Container implements ArrayAccess, ContainerContract
750 protected $resolved = array();
751 protected $bindings = array();
752 protected $instances = array();
753 protected $aliases = array();
754 protected $extenders = array();
755 protected $tags = array();
756 protected $buildStack = array();
757 public $contextual = array();
758 protected $reboundCallbacks = array();
759 protected $globalResolvingCallbacks = array();
760 protected $globalAfterResolvingCallbacks = array();
761 protected $resolvingCallbacks = array();
762 protected $afterResolvingCallbacks = array();
763 public function when($concrete)
769 return $this->bound($abstract);
773 return isset($this->bindings[$abstract]) || isset($this->instances[$abstract]) || $this->isAlias($abstract);
777 return isset($this->resolved[$abstract]) || isset($this->instances[$abstract]);
781 return isset($this->aliases[$name]);
783 public function bind($abstract, $concrete = null, $shared =
false)
785 if (is_array($abstract)) {
786 list($abstract, $alias) = $this->extractAlias($abstract);
787 $this->alias($abstract, $alias);
789 $this->dropStaleInstances($abstract);
790 if (is_null($concrete)) {
791 $concrete = $abstract;
793 if (!$concrete instanceof Closure) {
794 $concrete = $this->getClosure($abstract, $concrete);
796 $this->bindings[$abstract] = compact(
'concrete',
'shared');
797 if ($this->resolved($abstract)) {
798 $this->rebound($abstract);
803 return function (
$c, $parameters = array()) use($abstract, $concrete) {
804 $method = $abstract == $concrete ?
'build' :
'make';
805 return $c->{$method}($concrete, $parameters);
810 $this->contextual[$concrete][$abstract] = $implementation;
812 public function bindIf($abstract, $concrete = null, $shared =
false)
814 if (!$this->bound($abstract)) {
815 $this->bind($abstract, $concrete, $shared);
820 $this->bind($abstract, $concrete,
true);
822 public function share(Closure $closure)
826 if (is_null($object)) {
834 $this->bind($abstract, $this->share($closure),
true);
836 public function extend($abstract, Closure $closure)
838 if (isset($this->instances[$abstract])) {
839 $this->instances[$abstract] = $closure($this->instances[$abstract], $this);
840 $this->rebound($abstract);
842 $this->extenders[$abstract][] = $closure;
847 if (is_array($abstract)) {
848 list($abstract, $alias) = $this->extractAlias($abstract);
849 $this->alias($abstract, $alias);
851 unset($this->aliases[$abstract]);
852 $bound = $this->bound($abstract);
853 $this->instances[$abstract] = $instance;
855 $this->rebound($abstract);
858 public function tag($abstracts, $tags)
860 $tags = is_array($tags) ? $tags : array_slice(func_get_args(), 1);
861 foreach ($tags as
$tag) {
862 if (!isset($this->tags[$tag])) {
863 $this->tags[
$tag] = array();
865 foreach ((array) $abstracts as $abstract) {
866 $this->tags[
$tag][] = $abstract;
873 foreach ($this->tags[
$tag] as $abstract) {
874 $results[] = $this->make($abstract);
878 public function alias($abstract, $alias)
880 $this->aliases[$alias] = $abstract;
884 return array(key($definition), current($definition));
888 $this->reboundCallbacks[$abstract][] = $callback;
889 if ($this->bound($abstract)) {
890 return $this->make($abstract);
893 public function refresh($abstract, $target, $method)
895 return $this->rebinding($abstract,
function (
$app, $instance) use($target, $method) {
896 $target->{$method}($instance);
901 $instance = $this->make($abstract);
902 foreach ($this->getReboundCallbacks($abstract) as $callback) {
903 call_user_func($callback, $this, $instance);
908 if (isset($this->reboundCallbacks[$abstract])) {
909 return $this->reboundCallbacks[$abstract];
913 public function wrap(
Closure $callback, array $parameters = array())
915 return function () use($callback, $parameters) {
916 return $this->
call($callback, $parameters);
919 public function call($callback, array $parameters = array(), $defaultMethod = null)
921 if ($this->isCallableWithAtSign($callback) || $defaultMethod) {
922 return $this->callClass($callback, $parameters, $defaultMethod);
924 $dependencies = $this->getMethodDependencies($callback, $parameters);
925 return call_user_func_array($callback, $dependencies);
929 if (!is_string($callback)) {
932 return strpos($callback,
'@') !==
false;
936 $dependencies = array();
937 foreach ($this->getCallReflector($callback)->getParameters() as $key => $parameter) {
938 $this->addDependencyForCallParameter($parameter, $parameters, $dependencies);
940 return array_merge($dependencies, $parameters);
944 if (is_string($callback) && strpos($callback,
'::') !==
false) {
945 $callback = explode(
'::', $callback);
947 if (is_array($callback)) {
954 if (array_key_exists($parameter->name, $parameters)) {
955 $dependencies[] = $parameters[$parameter->name];
956 unset($parameters[$parameter->name]);
957 } elseif ($parameter->getClass()) {
958 $dependencies[] = $this->make($parameter->getClass()->name);
959 } elseif ($parameter->isDefaultValueAvailable()) {
960 $dependencies[] = $parameter->getDefaultValue();
963 protected function callClass($target, array $parameters = array(), $defaultMethod = null)
965 $segments = explode(
'@', $target);
966 $method = count($segments) == 2 ? $segments[1] : $defaultMethod;
967 if (is_null($method)) {
970 return $this->
call(array($this->make($segments[0]), $method), $parameters);
972 public function make($abstract, $parameters = array())
974 $abstract = $this->getAlias($abstract);
975 if (isset($this->instances[$abstract])) {
976 return $this->instances[$abstract];
978 $concrete = $this->getConcrete($abstract);
979 if ($this->isBuildable($concrete, $abstract)) {
980 $object = $this->build($concrete, $parameters);
982 $object = $this->make($concrete, $parameters);
984 foreach ($this->getExtenders($abstract) as $extender) {
985 $object = $extender($object, $this);
987 if ($this->isShared($abstract)) {
988 $this->instances[$abstract] = $object;
990 $this->fireResolvingCallbacks($abstract, $object);
991 $this->resolved[$abstract] =
true;
996 if (!is_null($concrete = $this->getContextualConcrete($abstract))) {
999 if (!isset($this->bindings[$abstract])) {
1000 if ($this->missingLeadingSlash($abstract) && isset($this->bindings[
'\\' . $abstract])) {
1001 $abstract =
'\\' . $abstract;
1005 return $this->bindings[$abstract][
'concrete'];
1009 if (isset($this->contextual[end($this->buildStack)][$abstract])) {
1010 return $this->contextual[end($this->buildStack)][$abstract];
1015 return is_string($abstract) && strpos($abstract,
'\\') !== 0;
1019 if (isset($this->extenders[$abstract])) {
1020 return $this->extenders[$abstract];
1024 public function build($concrete, $parameters = array())
1026 if ($concrete instanceof
Closure) {
1027 return $concrete($this, $parameters);
1030 if (!$reflector->isInstantiable()) {
1031 $message =
"Target [{$concrete}] is not instantiable.";
1034 $this->buildStack[] = $concrete;
1035 $constructor = $reflector->getConstructor();
1036 if (is_null($constructor)) {
1037 array_pop($this->buildStack);
1038 return new $concrete();
1040 $dependencies = $constructor->getParameters();
1041 $parameters = $this->keyParametersByArgument($dependencies, $parameters);
1042 $instances = $this->getDependencies($dependencies, $parameters);
1043 array_pop($this->buildStack);
1044 return $reflector->newInstanceArgs($instances);
1048 $dependencies = array();
1049 foreach ($parameters as $parameter) {
1050 $dependency = $parameter->getClass();
1051 if (array_key_exists($parameter->name, $primitives)) {
1052 $dependencies[] = $primitives[$parameter->name];
1053 } elseif (is_null($dependency)) {
1054 $dependencies[] = $this->resolveNonClass($parameter);
1056 $dependencies[] = $this->resolveClass($parameter);
1059 return (array) $dependencies;
1063 if ($parameter->isDefaultValueAvailable()) {
1064 return $parameter->getDefaultValue();
1066 $message =
"Unresolvable dependency resolving [{$parameter}] in class {$parameter->getDeclaringClass()->getName()}";
1072 return $this->make($parameter->getClass()->name);
1074 if ($parameter->isOptional()) {
1075 return $parameter->getDefaultValue();
1082 foreach ($parameters as $key => $value) {
1083 if (is_numeric($key)) {
1084 unset($parameters[$key]);
1085 $parameters[$dependencies[$key]->name] = $value;
1092 if ($callback === null && $abstract instanceof
Closure) {
1093 $this->resolvingCallback($abstract);
1095 $this->resolvingCallbacks[$abstract][] = $callback;
1100 if ($abstract instanceof
Closure && $callback === null) {
1101 $this->afterResolvingCallback($abstract);
1103 $this->afterResolvingCallbacks[$abstract][] = $callback;
1108 $abstract = $this->getFunctionHint($callback);
1110 $this->resolvingCallbacks[$abstract][] = $callback;
1112 $this->globalResolvingCallbacks[] = $callback;
1117 $abstract = $this->getFunctionHint($callback);
1119 $this->afterResolvingCallbacks[$abstract][] = $callback;
1121 $this->globalAfterResolvingCallbacks[] = $callback;
1127 if ($function->getNumberOfParameters() == 0) {
1130 $expected = $function->getParameters()[0];
1131 if (!$expected->getClass()) {
1134 return $expected->getClass()->name;
1138 $this->fireCallbackArray($object, $this->globalResolvingCallbacks);
1139 $this->fireCallbackArray($object, $this->getCallbacksForType($abstract, $object, $this->resolvingCallbacks));
1140 $this->fireCallbackArray($object, $this->globalAfterResolvingCallbacks);
1141 $this->fireCallbackArray($object, $this->getCallbacksForType($abstract, $object, $this->afterResolvingCallbacks));
1146 foreach ($callbacksPerType as $type => $callbacks) {
1147 if ($type === $abstract || $object instanceof $type) {
1148 $results = array_merge($results, $callbacks);
1155 foreach ($callbacks as $callback) {
1156 $callback($object, $this);
1161 if (isset($this->bindings[$abstract][
'shared'])) {
1162 $shared = $this->bindings[$abstract][
'shared'];
1166 return isset($this->instances[$abstract]) || $shared ===
true;
1170 return $concrete === $abstract || $concrete instanceof
Closure;
1174 return isset($this->aliases[$abstract]) ? $this->aliases[$abstract] : $abstract;
1178 return $this->bindings;
1182 unset($this->instances[$abstract], $this->aliases[$abstract]);
1186 unset($this->instances[$abstract]);
1190 $this->instances = array();
1194 $this->aliases = array();
1195 $this->resolved = array();
1196 $this->bindings = array();
1197 $this->instances = array();
1201 return static::$instance;
1209 return isset($this->bindings[$key]);
1213 return $this->make($key);
1217 if (!$value instanceof
Closure) {
1218 $value =
function () use($value) {
1222 $this->bind($key, $value);
1226 unset($this->bindings[$key], $this->instances[$key], $this->resolved[$key]);
1234 $this[$key] = $value;
1243 const MASTER_REQUEST = 1;
1244 const SUB_REQUEST = 2;
1245 public function handle(
Request $request, $type = self::MASTER_REQUEST, $catch =
true);
1273 protected $hasBeenBootstrapped =
false;
1274 protected $booted =
false;
1275 protected $bootingCallbacks = array();
1276 protected $bootedCallbacks = array();
1277 protected $terminatingCallbacks = array();
1278 protected $serviceProviders = array();
1279 protected $loadedProviders = array();
1280 protected $deferredServices = array();
1283 protected $useStoragePathForOptimizations =
false;
1284 protected $environmentFile =
'.env';
1287 $this->registerBaseBindings();
1288 $this->registerBaseServiceProviders();
1289 $this->registerCoreContainerAliases();
1300 static::setInstance($this);
1301 $this->instance(
'app', $this);
1302 $this->instance(
'Illuminate\\Container\\Container', $this);
1311 foreach ($bootstrappers as $bootstrapper) {
1312 $this[
'events']->fire(
'bootstrapping: ' . $bootstrapper, array($this));
1313 $this->make($bootstrapper)->bootstrap($this);
1314 $this[
'events']->fire(
'bootstrapped: ' . $bootstrapper, array($this));
1316 $this->hasBeenBootstrapped =
true;
1320 return $this->afterBootstrapping(
'Illuminate\\Foundation\\Bootstrap\\DetectEnvironment', $callback);
1324 $this[
'events']->listen(
'bootstrapping: ' . $bootstrapper, $callback);
1328 $this[
'events']->listen(
'bootstrapped: ' . $bootstrapper, $callback);
1332 return $this->hasBeenBootstrapped;
1337 $this->bindPathsInContainer();
1342 $this->instance(
'path', $this->
path());
1343 foreach (array(
'base',
'config',
'database',
'lang',
'public',
'storage') as
$path) {
1344 $this->instance(
'path.' . $path, $this->{$path .
'Path'}());
1349 return $this->basePath . DIRECTORY_SEPARATOR .
'app';
1357 return $this->basePath . DIRECTORY_SEPARATOR .
'config';
1361 return $this->databasePath ?: $this->basePath . DIRECTORY_SEPARATOR .
'database';
1365 $this->databasePath =
$path;
1366 $this->instance(
'path.database',
$path);
1371 return $this->basePath . DIRECTORY_SEPARATOR .
'resources' . DIRECTORY_SEPARATOR .
'lang';
1375 return $this->basePath . DIRECTORY_SEPARATOR .
'public';
1379 return $this->storagePath ?: $this->basePath . DIRECTORY_SEPARATOR .
'storage';
1383 $this->storagePath =
$path;
1384 $this->instance(
'path.storage',
$path);
1389 $this->environmentFile = $file;
1394 return $this->environmentFile ?:
'.env';
1398 if (func_num_args() > 0) {
1399 $patterns = is_array(func_get_arg(0)) ? func_get_arg(0) : func_get_args();
1400 foreach ($patterns as $pattern) {
1401 if (str_is($pattern, $this[
'env'])) {
1407 return $this[
'env'];
1411 return $this[
'env'] ==
'local';
1420 return php_sapi_name() ==
'cli';
1424 return $this[
'env'] ==
'testing';
1428 $manifestPath = $this->getCachedServicesPath();
1431 public function register($provider,
$options = array(), $force =
false)
1433 if ($registered = $this->getProvider($provider) && !$force) {
1436 if (is_string($provider)) {
1437 $provider = $this->resolveProviderClass($provider);
1439 $provider->register();
1440 foreach ($options as $key => $value) {
1441 $this[$key] = $value;
1443 $this->markAsRegistered($provider);
1444 if ($this->booted) {
1445 $this->bootProvider($provider);
1451 $name = is_string($provider) ? $provider : get_class($provider);
1452 return array_first($this->serviceProviders,
function ($key, $value) use($name) {
1453 return $value instanceof $name;
1458 return new $provider($this);
1462 $this[
'events']->fire($class = get_class($provider), array($provider));
1463 $this->serviceProviders[] = $provider;
1464 $this->loadedProviders[$class] =
true;
1468 foreach ($this->deferredServices as $service => $provider) {
1469 $this->loadDeferredProvider($service);
1471 $this->deferredServices = array();
1475 if (!isset($this->deferredServices[$service])) {
1478 $provider = $this->deferredServices[$service];
1479 if (!isset($this->loadedProviders[$provider])) {
1480 $this->registerDeferredProvider($provider, $service);
1486 unset($this->deferredServices[$service]);
1488 $this->
register($instance =
new $provider($this));
1489 if (!$this->booted) {
1490 $this->booting(
function () use($instance) {
1491 $this->bootProvider($instance);
1495 public function make($abstract, $parameters = array())
1497 $abstract = $this->getAlias($abstract);
1498 if (isset($this->deferredServices[$abstract])) {
1499 $this->loadDeferredProvider($abstract);
1501 return parent::make($abstract, $parameters);
1505 return isset($this->deferredServices[$abstract]) || parent::bound($abstract);
1509 return $this->booted;
1513 if ($this->booted) {
1516 $this->fireAppCallbacks($this->bootingCallbacks);
1517 array_walk($this->serviceProviders,
function ($p) {
1518 $this->bootProvider($p);
1520 $this->booted =
true;
1521 $this->fireAppCallbacks($this->bootedCallbacks);
1525 if (method_exists($provider,
'boot')) {
1526 return $this->
call(array($provider,
'boot'));
1531 $this->bootingCallbacks[] = $callback;
1535 $this->bootedCallbacks[] = $callback;
1536 if ($this->isBooted()) {
1537 $this->fireAppCallbacks(array($callback));
1540 public function handle(SymfonyRequest $request, $type = self::MASTER_REQUEST, $catch =
true)
1546 return $this[
'files']->exists($this->getCachedConfigPath());
1550 if ($this->vendorIsWritableForOptimizations()) {
1551 return $this->basePath() .
'/vendor/config.php';
1553 return $this[
'path.storage'] .
'/framework/config.php';
1558 return $this[
'files']->exists($this->getCachedRoutesPath());
1562 if ($this->vendorIsWritableForOptimizations()) {
1563 return $this->basePath() .
'/vendor/routes.php';
1565 return $this[
'path.storage'] .
'/framework/routes.php';
1570 if ($this->vendorIsWritableForOptimizations()) {
1571 return $this->basePath() .
'/vendor/compiled.php';
1573 return $this->storagePath() .
'/framework/compiled.php';
1578 if ($this->vendorIsWritableForOptimizations()) {
1579 return $this->basePath() .
'/vendor/services.json';
1581 return $this->storagePath() .
'/framework/services.json';
1586 if ($this->useStoragePathForOptimizations) {
1589 return is_writable($this->basePath() .
'/vendor');
1593 $this->useStoragePathForOptimizations = $value;
1598 foreach ($callbacks as $callback) {
1599 call_user_func($callback, $this);
1604 return file_exists($this->storagePath() . DIRECTORY_SEPARATOR .
'framework' . DIRECTORY_SEPARATOR .
'down');
1606 public function down(Closure $callback)
1608 $this[
'events']->listen(
'illuminate.app.down', $callback);
1610 public function abort(
$code, $message =
'', array $headers = array())
1619 $this->terminatingCallbacks[] = $callback;
1624 foreach ($this->terminatingCallbacks as $terminating) {
1625 $this->
call($terminating);
1630 return $this->loadedProviders;
1634 $this->deferredServices = $services;
1638 return isset($this->deferredServices[$service]);
1642 return $this[
'config']->get(
'app.locale');
1646 $this[
'config']->set(
'app.locale', $locale);
1647 $this[
'translator']->setLocale($locale);
1648 $this[
'events']->fire(
'locale.changed', array($locale));
1652 $aliases = array(
'app' => array(
'Illuminate\\Foundation\\Application',
'Illuminate\\Contracts\\Container\\Container',
'Illuminate\\Contracts\\Foundation\\Application'),
'artisan' => array(
'Illuminate\\Console\\Application',
'Illuminate\\Contracts\\Console\\Application'),
'auth' =>
'Illuminate\\Auth\\AuthManager',
'auth.driver' => array(
'Illuminate\\Auth\\Guard',
'Illuminate\\Contracts\\Auth\\Guard'),
'auth.password.tokens' =>
'Illuminate\\Auth\\Passwords\\TokenRepositoryInterface',
'blade.compiler' =>
'Illuminate\\View\\Compilers\\BladeCompiler',
'cache' => array(
'Illuminate\\Cache\\CacheManager',
'Illuminate\\Contracts\\Cache\\Factory'),
'cache.store' => array(
'Illuminate\\Cache\\Repository',
'Illuminate\\Contracts\\Cache\\Repository'),
'config' => array(
'Illuminate\\Config\\Repository',
'Illuminate\\Contracts\\Config\\Repository'),
'cookie' => array(
'Illuminate\\Cookie\\CookieJar',
'Illuminate\\Contracts\\Cookie\\Factory',
'Illuminate\\Contracts\\Cookie\\QueueingFactory'),
'encrypter' => array(
'Illuminate\\Encryption\\Encrypter',
'Illuminate\\Contracts\\Encryption\\Encrypter'),
'db' =>
'Illuminate\\Database\\DatabaseManager',
'events' => array(
'Illuminate\\Events\\Dispatcher',
'Illuminate\\Contracts\\Events\\Dispatcher'),
'files' =>
'Illuminate\\Filesystem\\Filesystem',
'filesystem' => array(
'Illuminate\\Filesystem\\FilesystemManager',
'Illuminate\\Contracts\\Filesystem\\Factory'),
'filesystem.disk' =>
'Illuminate\\Contracts\\Filesystem\\Filesystem',
'filesystem.cloud' =>
'Illuminate\\Contracts\\Filesystem\\Cloud',
'hash' =>
'Illuminate\\Contracts\\Hashing\\Hasher',
'translator' => array(
'Illuminate\\Translation\\Translator',
'Symfony\\Component\\Translation\\TranslatorInterface'),
'log' => array(
'Illuminate\\Log\\Writer',
'Illuminate\\Contracts\\Logging\\Log',
'Psr\\Log\\LoggerInterface'),
'mailer' => array(
'Illuminate\\Mail\\Mailer',
'Illuminate\\Contracts\\Mail\\Mailer',
'Illuminate\\Contracts\\Mail\\MailQueue'),
'paginator' =>
'Illuminate\\Pagination\\Factory',
'auth.password' => array(
'Illuminate\\Auth\\Passwords\\PasswordBroker',
'Illuminate\\Contracts\\Auth\\PasswordBroker'),
'queue' => array(
'Illuminate\\Queue\\QueueManager',
'Illuminate\\Contracts\\Queue\\Factory',
'Illuminate\\Contracts\\Queue\\Monitor'),
'queue.connection' =>
'Illuminate\\Contracts\\Queue\\Queue',
'redirect' =>
'Illuminate\\Routing\\Redirector',
'redis' => array(
'Illuminate\\Redis\\Database',
'Illuminate\\Contracts\\Redis\\Database'),
'request' =>
'Illuminate\\Http\\Request',
'router' => array(
'Illuminate\\Routing\\Router',
'Illuminate\\Contracts\\Routing\\Registrar'),
'session' =>
'Illuminate\\Session\\SessionManager',
'session.store' => array(
'Illuminate\\Session\\Store',
'Symfony\\Component\\HttpFoundation\\Session\\SessionInterface'),
'url' => array(
'Illuminate\\Routing\\UrlGenerator',
'Illuminate\\Contracts\\Routing\\UrlGenerator'),
'validator' => array(
'Illuminate\\Validation\\Factory',
'Illuminate\\Contracts\\Validation\\Factory'),
'view' => array(
'Illuminate\\View\\Factory',
'Illuminate\\Contracts\\View\\Factory'));
1653 foreach ($aliases as $key => $aliases) {
1654 foreach ((array) $aliases as $alias) {
1655 $this->alias($key, $alias);
1662 $this->loadedProviders = array();
1670 public function detect(Closure $callback, $consoleArgs = null)
1673 return $this->detectConsoleEnvironment($callback, $consoleArgs);
1675 return $this->detectWebEnvironment($callback);
1679 return call_user_func($callback);
1683 if (!is_null($value = $this->getEnvironmentArgument($args))) {
1684 return head(array_slice(explode(
'=', $value), 1));
1686 return $this->detectWebEnvironment($callback);
1690 return array_first($args,
function ($k, $v) {
1691 return starts_with($v,
'--env');
1704 $this->configureHandlers($app, $this->registerLogger($app));
1705 $app->
bind(
'Psr\\Log\\LoggerInterface',
function ($app) {
1706 return $app[
'log']->getMonolog();
1716 $method =
'configure' . ucfirst($app[
'config'][
'app.log']) .
'Handler';
1717 $this->{$method}(
$app, $log);
1721 $log->
useFiles($app->storagePath() .
'/logs/laravel.log');
1725 $log->
useDailyFiles($app->storagePath() .
'/logs/laravel.log', $app->
make(
'config')->get(
'app.log_max_files', 5));
1748 error_reporting(-1);
1749 set_error_handler(array($this,
'handleError'));
1750 set_exception_handler(array($this,
'handleException'));
1751 register_shutdown_function(array($this,
'handleShutdown'));
1753 ini_set(
'display_errors',
'Off');
1756 public function handleError($level, $message, $file =
'', $line = 0, $context = array())
1758 if (error_reporting() & $level) {
1759 throw new ErrorException($message, 0, $level, $file, $line);
1764 $this->getExceptionHandler()->report($e);
1765 if ($this->app->runningInConsole()) {
1766 $this->renderForConsole($e);
1768 $this->renderHttpResponse($e);
1773 $this->getExceptionHandler()->renderForConsole(
new ConsoleOutput(), $e);
1777 $this->getExceptionHandler()->render($this->app[
'request'], $e)->send();
1781 if (!is_null($error = error_get_last()) && $this->isFatal($error[
'type'])) {
1782 $this->handleException($this->fatalExceptionFromError($error, 0));
1787 return new FatalErrorException($error[
'message'], $error[
'type'], 0, $error[
'file'], $error[
'line'], $traceOffset);
1791 return in_array($type, array(E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE));
1795 return $this->app->make(
'Illuminate\\Contracts\\Debug\\ExceptionHandler');
1807 Facade::clearResolvedInstances();
1808 Facade::setFacadeApplication($app);
1809 AliasLoader::getInstance($app[
'config'][
'app.aliases'])->register();
1844 if (file_exists($cached = $app->getCachedConfigPath())) {
1845 $items = (require $cached);
1846 $loadedFromCache =
true;
1849 if (!isset($loadedFromCache)) {
1850 $this->loadConfigurationFiles($app, $config);
1852 date_default_timezone_set($config[
'app.timezone']);
1853 mb_internal_encoding(
'UTF-8');
1857 foreach ($this->getConfigurationFiles($app) as $key =>
$path) {
1858 $config->set($key, require
$path);
1864 foreach (Finder::create()->files()->
name(
'*.php')->in($app->configPath()) as $file) {
1865 $nesting = $this->getConfigurationNesting($file);
1866 $files[$nesting . basename($file->getRealPath(),
'.php')] = $file->getRealPath();
1870 private function getConfigurationNesting(
SplFileInfo $file)
1872 $directory = dirname($file->getRealPath());
1873 if ($tree = trim(str_replace(config_path(),
'', $directory), DIRECTORY_SEPARATOR)) {
1874 $tree = str_replace(DIRECTORY_SEPARATOR,
'.', $tree) .
'.';
1890 }
catch (InvalidArgumentException $e) {
1892 $app->detectEnvironment(
function () {
1893 return env(
'APP_ENV',
'production');
1910 protected $bootstrappers = array(
'Illuminate\\Foundation\\Bootstrap\\DetectEnvironment',
'Illuminate\\Foundation\\Bootstrap\\LoadConfiguration',
'Illuminate\\Foundation\\Bootstrap\\ConfigureLogging',
'Illuminate\\Foundation\\Bootstrap\\HandleExceptions',
'Illuminate\\Foundation\\Bootstrap\\RegisterFacades',
'Illuminate\\Foundation\\Bootstrap\\RegisterProviders',
'Illuminate\\Foundation\\Bootstrap\\BootProviders');
1911 protected $middleware = array();
1912 protected $routeMiddleware = array();
1916 $this->router = $router;
1917 foreach ($this->routeMiddleware as $key => $middleware) {
1924 $response = $this->sendRequestThroughRouter($request);
1925 }
catch (Exception $e) {
1926 $this->reportException($e);
1927 $response = $this->renderException($request, $e);
1929 $this->app[
'events']->fire(
'kernel.handled', array($request,
$response));
1934 $this->app->instance(
'request', $request);
1935 Facade::clearResolvedInstance(
'request');
1937 return (
new Pipeline($this->app))->send($request)->through($this->middleware)->then($this->dispatchToRouter());
1941 $routeMiddlewares = $this->gatherRouteMiddlewares($request);
1942 foreach (array_merge($routeMiddlewares, $this->middleware) as $middleware) {
1943 $instance = $this->app->make($middleware);
1945 $instance->terminate($request,
$response);
1948 $this->app->terminate();
1952 if ($request->route()) {
1953 return $this->router->gatherRouteMiddlewares($request->route());
1959 if (array_search($middleware, $this->middleware) ===
false) {
1960 array_unshift($this->middleware, $middleware);
1966 if (array_search($middleware, $this->middleware) ===
false) {
1967 $this->middleware[] = $middleware;
1973 if (!$this->app->hasBeenBootstrapped()) {
1974 $this->app->bootstrapWith($this->bootstrappers());
1979 return function ($request) {
1980 $this->app->instance(
'request', $request);
1981 return $this->router->dispatch($request);
1986 return $this->bootstrappers;
1990 $this->app[
'Illuminate\\Contracts\\Debug\\ExceptionHandler']->report($e);
1994 return $this->app[
'Illuminate\\Contracts\\Debug\\ExceptionHandler']->render($request, $e);
2012 return view(
'auth.register');
2016 $validator = $this->registrar->validator($request->
all());
2017 if ($validator->fails()) {
2018 $this->throwValidationException($request, $validator);
2020 $this->auth->login($this->registrar->create($request->
all()));
2025 return view(
'auth.login');
2029 $this->validate($request, array(
'email' =>
'required|email',
'password' =>
'required'));
2030 $credentials = $request->
only(
'email',
'password');
2031 if ($this->auth->attempt($credentials, $request->
has(
'remember'))) {
2038 return 'These credentials do not match our records.';
2042 $this->auth->logout();
2043 return redirect(property_exists($this,
'redirectAfterLogout') ? $this->redirectAfterLogout :
'/');
2047 if (property_exists($this,
'redirectPath')) {
2048 return $this->redirectPath;
2050 return property_exists($this,
'redirectTo') ? $this->redirectTo :
'/home';
2054 return property_exists($this,
'loginPath') ? $this->
loginPath :
'/auth/login';
2069 return view(
'auth.password');
2073 $this->validate($request, array(
'email' =>
'required|email'));
2074 $response = $this->passwords->sendResetLink($request->
only(
'email'),
function ($m) {
2079 return redirect()->back()->with(
'status', trans(
$response));
2081 return redirect()->back()->withErrors(array(
'email' => trans(
$response)));
2086 return isset($this->subject) ? $this->subject :
'Your Password Reset Link';
2090 if (is_null($token)) {
2093 return view(
'auth.reset')->with(
'token', $token);
2097 $this->validate($request, array(
'token' =>
'required',
'email' =>
'required|email',
'password' =>
'required|confirmed'));
2098 $credentials = $request->
only(
'email',
'password',
'password_confirmation',
'token');
2099 $response = $this->passwords->reset($credentials,
function ($user, $password) {
2100 $user->password = bcrypt($password);
2102 $this->auth->login($user);
2108 return redirect()->back()->withInput($request->
only(
'email'))->withErrors(array(
'email' => trans(
$response)));
2113 if (property_exists($this,
'redirectPath')) {
2114 return $this->redirectPath;
2116 return property_exists($this,
'redirectTo') ? $this->redirectTo :
'/home';
2127 class Request extends SymfonyRequest implements ArrayAccess
2135 static::enableHttpMethodParameterOverride();
2136 return static::createFromBase(SymfonyRequest::createFromGlobals());
2144 return $this->getMethod();
2148 return rtrim($this->getSchemeAndHttpHost() . $this->getBaseUrl(),
'/');
2152 return rtrim(preg_replace(
'/\\?.*/',
'', $this->getUri()),
'/');
2156 $query = $this->getQueryString();
2157 return $query ? $this->
url() .
'?' . $query : $this->
url();
2161 $pattern = trim($this->getPathInfo(),
'/');
2162 return $pattern ==
'' ?
'/' : $pattern;
2166 return rawurldecode($this->
path());
2170 return array_get($this->segments(), $index - 1, $default);
2174 $segments = explode(
'/', $this->
path());
2175 return array_values(array_filter($segments,
function ($v) {
2181 foreach (func_get_args() as $pattern) {
2182 if (str_is($pattern, urldecode($this->
path()))) {
2190 return $this->isXmlHttpRequest();
2194 return $this->headers->get(
'X-PJAX') ==
true;
2198 return $this->isSecure();
2202 return $this->getClientIp();
2206 return $this->getClientIps();
2210 $keys = is_array($key) ? $key : func_get_args();
2211 $input = $this->all();
2212 foreach ($keys as $value) {
2213 if (!array_key_exists($value, $input)) {
2221 $keys = is_array($key) ? $key : func_get_args();
2222 foreach ($keys as $value) {
2223 if ($this->isEmptyString($value)) {
2231 $boolOrArray = is_bool($this->input($key)) || is_array($this->input($key));
2232 return !$boolOrArray && trim((
string) $this->input($key)) ===
'';
2236 return array_replace_recursive($this->input(), $this->files->all());
2238 public function input($key = null, $default = null)
2240 $input = $this->getInputSource()->all() + $this->query->all();
2241 return array_get($input, $key, $default);
2245 $keys = is_array($keys) ? $keys : func_get_args();
2247 $input = $this->all();
2248 foreach ($keys as $key) {
2249 array_set($results, $key, array_get($input, $key));
2255 $keys = is_array($keys) ? $keys : func_get_args();
2256 $results = $this->all();
2257 array_forget($results, $keys);
2260 public function query($key = null, $default = null)
2262 return $this->retrieveItem(
'query', $key, $default);
2266 return !is_null($this->cookie($key));
2268 public function cookie($key = null, $default = null)
2270 return $this->retrieveItem(
'cookies', $key, $default);
2272 public function file($key = null, $default = null)
2274 return array_get($this->files->all(), $key, $default);
2278 if (!is_array($files = $this->file($key))) {
2279 $files = array($files);
2281 foreach ($files as $file) {
2282 if ($this->isValidFile($file)) {
2290 return $file instanceof SplFileInfo && $file->getPath() !=
'';
2292 public function header($key = null, $default = null)
2294 return $this->retrieveItem(
'headers', $key, $default);
2296 public function server($key = null, $default = null)
2298 return $this->retrieveItem(
'server', $key, $default);
2300 public function old($key = null, $default = null)
2302 return $this->
session()->getOldInput($key, $default);
2306 $flash = !is_null(
$filter) ? $this->{
$filter}($keys) : $this->input();
2307 $this->
session()->flashInput($flash);
2311 $keys = is_array($keys) ? $keys : func_get_args();
2312 return $this->flash(
'only', $keys);
2316 $keys = is_array($keys) ? $keys : func_get_args();
2317 return $this->flash(
'except', $keys);
2321 $this->
session()->flashInput(array());
2325 if (is_null($key)) {
2326 return $this->{$source}->all();
2328 return $this->{$source}->get($key, $default,
true);
2332 $this->getInputSource()->add($input);
2336 $this->getInputSource()->replace($input);
2338 public function json($key = null, $default = null)
2340 if (!isset($this->
json)) {
2341 $this->
json =
new ParameterBag((array) json_decode($this->getContent(),
true));
2343 if (is_null($key)) {
2346 return array_get($this->
json->all(), $key, $default);
2351 return $this->
json();
2353 return $this->getMethod() ==
'GET' ? $this->query : $this->request;
2357 return str_contains($this->header(
'CONTENT_TYPE'),
'/json');
2361 $acceptable = $this->getAcceptableContentTypes();
2362 return isset($acceptable[0]) && $acceptable[0] ==
'application/json';
2366 foreach ($this->getAcceptableContentTypes() as $type) {
2367 if ($format = $this->getFormat($type)) {
2375 if ($request instanceof
static) {
2378 $content = $request->content;
2379 $request = (
new static())->duplicate($request->query->all(), $request->request->all(), $request->attributes->all(), $request->cookies->all(), $request->files->all(), $request->server->all());
2380 $request->content = $content;
2381 $request->request = $request->getInputSource();
2384 public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
2386 return parent::duplicate($query, $request, $attributes, $cookies, array_filter((array) $files), $server);
2390 if (!$this->hasSession()) {
2391 throw new RuntimeException(
'Session store not set on request.');
2393 return $this->getSession();
2397 return call_user_func($this->getUserResolver());
2401 if (func_num_args() == 1) {
2402 return $this->
route()->parameter(func_get_arg(0));
2404 return call_user_func($this->getRouteResolver());
2409 return $this->userResolver ?:
function () {
2414 $this->userResolver = $callback;
2419 return $this->routeResolver ?:
function () {
2424 $this->routeResolver = $callback;
2429 return array_key_exists($offset, $this->all());
2433 return $this->input($offset);
2437 return $this->getInputSource()->set($offset, $value);
2441 return $this->getInputSource()->remove($offset);
2445 $input = $this->input();
2446 if (array_key_exists($key, $input)) {
2447 return $this->input($key);
2448 } elseif (!is_null($this->
route())) {
2449 return $this->
route()->parameter($key);
2459 public function handle($request, Closure $next)
2462 $response->headers->set(
'X-Frame-Options',
'SAMEORIGIN',
false);
2479 $this->encrypter = $encrypter;
2481 public function handle($request, Closure $next)
2483 if ($this->isReading($request) || $this->tokensMatch($request)) {
2484 return $this->addCookieToResponse($request, $next($request));
2490 $token = $request->input(
'_token') ?: $request->header(
'X-CSRF-TOKEN');
2491 if (!$token && ($header = $request->header(
'X-XSRF-TOKEN'))) {
2492 $token = $this->encrypter->decrypt($header);
2494 return StringUtils::equals($request->session()->token(), $token);
2498 $response->headers->setCookie(
new Cookie(
'XSRF-TOKEN', $request->session()->token(), time() + 60 * 120,
'/', null,
false,
false));
2503 return in_array($request->method(), array(
'HEAD',
'GET',
'OPTIONS'));
2519 public function handle($request, Closure $next)
2521 if ($this->app->isDownForMaintenance()) {
2524 return $next($request);
2532 const HEADER_CLIENT_IP =
'client_ip';
2533 const HEADER_CLIENT_HOST =
'client_host';
2534 const HEADER_CLIENT_PROTO =
'client_proto';
2535 const HEADER_CLIENT_PORT =
'client_port';
2536 const METHOD_HEAD =
'HEAD';
2537 const METHOD_GET =
'GET';
2538 const METHOD_POST =
'POST';
2539 const METHOD_PUT =
'PUT';
2540 const METHOD_PATCH =
'PATCH';
2541 const METHOD_DELETE =
'DELETE';
2542 const METHOD_PURGE =
'PURGE';
2543 const METHOD_OPTIONS =
'OPTIONS';
2544 const METHOD_TRACE =
'TRACE';
2545 const METHOD_CONNECT =
'CONNECT';
2546 protected static $trustedProxies = array();
2547 protected static $trustedHostPatterns = array();
2548 protected static $trustedHosts = array();
2549 protected static $trustedHeaders = array(self::HEADER_CLIENT_IP =>
'X_FORWARDED_FOR', self::HEADER_CLIENT_HOST =>
'X_FORWARDED_HOST', self::HEADER_CLIENT_PROTO =>
'X_FORWARDED_PROTO', self::HEADER_CLIENT_PORT =>
'X_FORWARDED_PORT');
2550 protected static $httpMethodParameterOverride =
false;
2571 protected $defaultLocale =
'en';
2574 public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
2576 $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
2578 public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
2584 $this->files =
new FileBag($files);
2586 $this->headers =
new HeaderBag($this->server->getHeaders());
2587 $this->content = $content;
2588 $this->languages = null;
2589 $this->charsets = null;
2590 $this->encodings = null;
2591 $this->acceptableContentTypes = null;
2592 $this->pathInfo = null;
2593 $this->requestUri = null;
2594 $this->baseUrl = null;
2595 $this->basePath = null;
2596 $this->method = null;
2602 if (
'cli-server' === php_sapi_name()) {
2603 if (array_key_exists(
'HTTP_CONTENT_LENGTH',
$_SERVER)) {
2604 $server[
'CONTENT_LENGTH'] =
$_SERVER[
'HTTP_CONTENT_LENGTH'];
2606 if (array_key_exists(
'HTTP_CONTENT_TYPE',
$_SERVER)) {
2607 $server[
'CONTENT_TYPE'] =
$_SERVER[
'HTTP_CONTENT_TYPE'];
2611 if (0 === strpos($request->headers->get(
'CONTENT_TYPE'),
'application/x-www-form-urlencoded') && in_array(strtoupper($request->server->get(
'REQUEST_METHOD',
'GET')), array(
'PUT',
'DELETE',
'PATCH'))) {
2612 parse_str($request->getContent(), $data);
2617 public static function create(
$uri, $method =
'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
2619 $server = array_replace(array(
'SERVER_NAME' =>
'localhost',
'SERVER_PORT' => 80,
'HTTP_HOST' =>
'localhost',
'HTTP_USER_AGENT' =>
'Symfony/2.X',
'HTTP_ACCEPT' =>
'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'HTTP_ACCEPT_LANGUAGE' =>
'en-us,en;q=0.5',
'HTTP_ACCEPT_CHARSET' =>
'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'REMOTE_ADDR' =>
'127.0.0.1',
'SCRIPT_NAME' =>
'',
'SCRIPT_FILENAME' =>
'',
'SERVER_PROTOCOL' =>
'HTTP/1.1',
'REQUEST_TIME' => time()), $server);
2620 $server[
'PATH_INFO'] =
'';
2621 $server[
'REQUEST_METHOD'] = strtoupper($method);
2622 $components = parse_url(
$uri);
2623 if (isset($components[
'host'])) {
2624 $server[
'SERVER_NAME'] = $components[
'host'];
2625 $server[
'HTTP_HOST'] = $components[
'host'];
2627 if (isset($components[
'scheme'])) {
2628 if (
'https' === $components[
'scheme']) {
2629 $server[
'HTTPS'] =
'on';
2630 $server[
'SERVER_PORT'] = 443;
2632 unset($server[
'HTTPS']);
2633 $server[
'SERVER_PORT'] = 80;
2636 if (isset($components[
'port'])) {
2637 $server[
'SERVER_PORT'] = $components[
'port'];
2638 $server[
'HTTP_HOST'] = $server[
'HTTP_HOST'] .
':' . $components[
'port'];
2640 if (isset($components[
'user'])) {
2641 $server[
'PHP_AUTH_USER'] = $components[
'user'];
2643 if (isset($components[
'pass'])) {
2644 $server[
'PHP_AUTH_PW'] = $components[
'pass'];
2646 if (!isset($components[
'path'])) {
2647 $components[
'path'] =
'/';
2649 switch (strtoupper($method)) {
2653 if (!isset($server[
'CONTENT_TYPE'])) {
2654 $server[
'CONTENT_TYPE'] =
'application/x-www-form-urlencoded';
2657 $request = $parameters;
2662 $query = $parameters;
2666 if (isset($components[
'query'])) {
2667 parse_str(html_entity_decode($components[
'query']), $qs);
2669 $query = array_replace($qs, $query);
2670 $queryString = http_build_query($query,
'',
'&');
2673 $queryString = $components[
'query'];
2676 $queryString = http_build_query($query,
'',
'&');
2678 $server[
'REQUEST_URI'] = $components[
'path'] . (
'' !== $queryString ?
'?' . $queryString :
'');
2679 $server[
'QUERY_STRING'] = $queryString;
2680 return self::createRequestFromFactory($query, $request, array(), $cookies, $files, $server, $content);
2684 self::$requestFactory = $callable;
2686 public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
2689 if ($query !== null) {
2692 if ($request !== null) {
2695 if ($attributes !== null) {
2698 if ($cookies !== null) {
2701 if ($files !== null) {
2702 $dup->files =
new FileBag($files);
2704 if ($server !== null) {
2706 $dup->headers =
new HeaderBag($dup->server->getHeaders());
2708 $dup->languages = null;
2709 $dup->charsets = null;
2710 $dup->encodings = null;
2711 $dup->acceptableContentTypes = null;
2712 $dup->pathInfo = null;
2713 $dup->requestUri = null;
2714 $dup->baseUrl = null;
2715 $dup->basePath = null;
2716 $dup->method = null;
2717 $dup->format = null;
2718 if (!$dup->get(
'_format') && $this->
get(
'_format')) {
2719 $dup->attributes->
set(
'_format', $this->
get(
'_format'));
2721 if (!$dup->getRequestFormat(null)) {
2722 $dup->setRequestFormat($this->getRequestFormat(null));
2728 $this->query = clone $this->query;
2729 $this->request = clone $this->request;
2730 $this->attributes = clone $this->attributes;
2731 $this->cookies = clone $this->cookies;
2732 $this->files = clone $this->files;
2733 $this->server = clone $this->server;
2734 $this->headers = clone $this->headers;
2738 return sprintf(
'%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get(
'SERVER_PROTOCOL')) .
'
2739 ' . $this->headers .
'
2740 ' . $this->getContent();
2744 $this->server->set(
'QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), null,
'&')));
2745 $_GET = $this->query->all();
2746 $_POST = $this->request->all();
2749 foreach ($this->headers->all() as $key => $value) {
2750 $key = strtoupper(str_replace(
'-',
'_', $key));
2751 if (in_array($key, array(
'CONTENT_TYPE',
'CONTENT_LENGTH'))) {
2752 $_SERVER[$key] = implode(
', ', $value);
2754 $_SERVER[
'HTTP_' . $key] = implode(
', ', $value);
2758 $requestOrder = ini_get(
'request_order') ?: ini_get(
'variables_order');
2759 $requestOrder = preg_replace(
'#[^cgp]#',
'', strtolower($requestOrder)) ?:
'gp';
2761 foreach (str_split($requestOrder) as $order) {
2767 self::$trustedProxies = $proxies;
2771 return self::$trustedProxies;
2775 self::$trustedHostPatterns = array_map(
function ($hostPattern) {
2776 return sprintf(
'{%s}i', str_replace(
'}',
'\\}', $hostPattern));
2778 self::$trustedHosts = array();
2782 return self::$trustedHostPatterns;
2786 if (!array_key_exists($key, self::$trustedHeaders)) {
2787 throw new \InvalidArgumentException(sprintf(
'Unable to set the trusted header name for key "%s".', $key));
2789 self::$trustedHeaders[$key] = $value;
2793 if (!array_key_exists($key, self::$trustedHeaders)) {
2794 throw new \InvalidArgumentException(sprintf(
'Unable to get the trusted header name for key "%s".', $key));
2796 return self::$trustedHeaders[$key];
2805 foreach (explode(
'&', $qs) as $param) {
2806 if (
'' === $param ||
'=' === $param[0]) {
2809 $keyValuePair = explode(
'=', $param, 2);
2810 $parts[] = isset($keyValuePair[1]) ? rawurlencode(urldecode($keyValuePair[0])) .
'=' . rawurlencode(urldecode($keyValuePair[1])) : rawurlencode(urldecode($keyValuePair[0]));
2811 $order[] = urldecode($keyValuePair[0]);
2813 array_multisort($order, SORT_ASC, $parts);
2814 return implode(
'&', $parts);
2818 self::$httpMethodParameterOverride =
true;
2822 return self::$httpMethodParameterOverride;
2824 public function get($key, $default = null, $deep =
false)
2826 if ($this !== ($result = $this->query->get($key, $this, $deep))) {
2829 if ($this !== ($result = $this->attributes->get($key, $this, $deep))) {
2832 if ($this !== ($result = $this->request->get($key, $this, $deep))) {
2839 return $this->session;
2843 return $this->hasSession() && $this->cookies->has($this->
session->getName());
2847 return null !== $this->session;
2855 $ip = $this->server->get(
'REMOTE_ADDR');
2856 if (!$this->isFromTrustedProxy()) {
2859 if (!self::$trustedHeaders[self::HEADER_CLIENT_IP] || !$this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP])) {
2862 $clientIps = array_map(
'trim', explode(
',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP])));
2864 $ip = $clientIps[0];
2865 foreach ($clientIps as $key => $clientIp) {
2866 if (preg_match(
'{((?:\\d+\\.){3}\\d+)\\:\\d+}', $clientIp, $match)) {
2867 $clientIps[$key] = $clientIp = $match[1];
2869 if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
2870 unset($clientIps[$key]);
2873 return $clientIps ? array_reverse($clientIps) : array($ip);
2877 $ipAddresses = $this->getClientIps();
2878 return $ipAddresses[0];
2882 return $this->server->get(
'SCRIPT_NAME', $this->server->get(
'ORIG_SCRIPT_NAME',
''));
2886 if (null === $this->pathInfo) {
2887 $this->pathInfo = $this->preparePathInfo();
2889 return $this->pathInfo;
2893 if (null === $this->basePath) {
2894 $this->basePath = $this->prepareBasePath();
2900 if (null === $this->baseUrl) {
2901 $this->baseUrl = $this->prepareBaseUrl();
2903 return $this->baseUrl;
2907 return $this->isSecure() ?
'https' :
'http';
2911 if ($this->isFromTrustedProxy()) {
2912 if (self::$trustedHeaders[self::HEADER_CLIENT_PORT] && ($port = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PORT]))) {
2915 if (self::$trustedHeaders[self::HEADER_CLIENT_PROTO] &&
'https' === $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PROTO],
'http')) {
2919 if ($host = $this->headers->get(
'HOST')) {
2920 if ($host[0] ===
'[') {
2921 $pos = strpos($host,
':', strrpos($host,
']'));
2923 $pos = strrpos($host,
':');
2925 if (
false !== $pos) {
2926 return (
int) substr($host, $pos + 1);
2928 return 'https' === $this->getScheme() ? 443 : 80;
2930 return $this->server->get(
'SERVER_PORT');
2934 return $this->headers->get(
'PHP_AUTH_USER');
2938 return $this->headers->get(
'PHP_AUTH_PW');
2942 $userinfo = $this->getUser();
2943 $pass = $this->getPassword();
2945 $userinfo .=
":{$pass}";
2951 $scheme = $this->getScheme();
2952 $port = $this->getPort();
2953 if (
'http' == $scheme && $port == 80 ||
'https' == $scheme && $port == 443) {
2954 return $this->getHost();
2956 return $this->getHost() .
':' . $port;
2960 if (null === $this->requestUri) {
2961 $this->requestUri = $this->prepareRequestUri();
2963 return $this->requestUri;
2967 return $this->getScheme() .
'://' . $this->getHttpHost();
2971 if (null !== ($qs = $this->getQueryString())) {
2974 return $this->getSchemeAndHttpHost() . $this->getBaseUrl() . $this->getPathInfo() . $qs;
2978 return $this->getSchemeAndHttpHost() . $this->getBaseUrl() .
$path;
2982 $qs = static::normalizeQueryString($this->server->get(
'QUERY_STRING'));
2983 return '' === $qs ? null : $qs;
2987 if ($this->isFromTrustedProxy() && self::$trustedHeaders[self::HEADER_CLIENT_PROTO] && ($proto = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PROTO]))) {
2988 return in_array(strtolower(current(explode(
',', $proto))), array(
'https',
'on',
'ssl',
'1'));
2990 $https = $this->server->get(
'HTTPS');
2991 return !
empty($https) &&
'off' !== strtolower($https);
2995 if ($this->isFromTrustedProxy() && self::$trustedHeaders[self::HEADER_CLIENT_HOST] && ($host = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_HOST]))) {
2996 $elements = explode(
',', $host);
2997 $host = $elements[count($elements) - 1];
2998 } elseif (!($host = $this->headers->get(
'HOST'))) {
2999 if (!($host = $this->server->get(
'SERVER_NAME'))) {
3000 $host = $this->server->get(
'SERVER_ADDR',
'');
3003 $host = strtolower(preg_replace(
'/:\\d+$/',
'', trim($host)));
3004 if ($host &&
'' !== preg_replace(
'/(?:^\\[)?[a-zA-Z0-9-:\\]_]+\\.?/',
'', $host)) {
3005 throw new \UnexpectedValueException(sprintf(
'Invalid Host "%s"', $host));
3007 if (count(self::$trustedHostPatterns) > 0) {
3008 if (in_array($host, self::$trustedHosts)) {
3011 foreach (self::$trustedHostPatterns as $pattern) {
3012 if (preg_match($pattern, $host)) {
3013 self::$trustedHosts[] = $host;
3017 throw new \UnexpectedValueException(sprintf(
'Untrusted Host "%s"', $host));
3023 $this->method = null;
3024 $this->server->set(
'REQUEST_METHOD', $method);
3028 if (null === $this->method) {
3029 $this->method = strtoupper($this->server->get(
'REQUEST_METHOD',
'GET'));
3030 if (
'POST' === $this->method) {
3031 if ($method = $this->headers->get(
'X-HTTP-METHOD-OVERRIDE')) {
3032 $this->method = strtoupper($method);
3033 } elseif (self::$httpMethodParameterOverride) {
3034 $this->method = strtoupper($this->request->get(
'_method', $this->query->get(
'_method',
'POST')));
3038 return $this->method;
3042 return strtoupper($this->server->get(
'REQUEST_METHOD',
'GET'));
3046 if (null === static::$formats) {
3047 static::initializeFormats();
3049 return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
3053 if (
false !== ($pos = strpos($mimeType,
';'))) {
3054 $mimeType = substr($mimeType, 0, $pos);
3056 if (null === static::$formats) {
3057 static::initializeFormats();
3059 foreach (static::$formats as $format => $mimeTypes) {
3060 if (in_array($mimeType, (array) $mimeTypes)) {
3067 if (null === static::$formats) {
3068 static::initializeFormats();
3070 static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
3074 if (null === $this->
format) {
3075 $this->
format = $this->
get(
'_format', $default);
3077 return $this->format;
3085 return $this->getFormat($this->headers->get(
'CONTENT_TYPE'));
3089 $this->defaultLocale = $locale;
3090 if (null === $this->
locale) {
3091 $this->setPhpDefaultLocale($locale);
3096 return $this->defaultLocale;
3100 $this->setPhpDefaultLocale($this->
locale = $locale);
3104 return null === $this->
locale ? $this->defaultLocale : $this->locale;
3108 return $this->getMethod() === strtoupper($method);
3112 return in_array($this->getMethod(), array(
'GET',
'HEAD'));
3116 if (
false === $this->content ||
true === $asResource && null !== $this->content) {
3117 throw new \LogicException(
'getContent() can only be called once when using the resource return type.');
3119 if (
true === $asResource) {
3120 $this->content =
false;
3121 return fopen(
'php://input',
'rb');
3123 if (null === $this->content) {
3124 $this->content = file_get_contents(
'php://input');
3126 return $this->content;
3130 return preg_split(
'/\\s*,\\s*/', $this->headers->get(
'if_none_match'), null, PREG_SPLIT_NO_EMPTY);
3134 return $this->headers->hasCacheControlDirective(
'no-cache') ||
'no-cache' == $this->headers->get(
'Pragma');
3138 $preferredLanguages = $this->getLanguages();
3139 if (
empty($locales)) {
3140 return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
3142 if (!$preferredLanguages) {
3145 $extendedPreferredLanguages = array();
3146 foreach ($preferredLanguages as $language) {
3147 $extendedPreferredLanguages[] = $language;
3148 if (
false !== ($position = strpos($language,
'_'))) {
3149 $superLanguage = substr($language, 0, $position);
3150 if (!in_array($superLanguage, $preferredLanguages)) {
3151 $extendedPreferredLanguages[] = $superLanguage;
3155 $preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales));
3156 return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
3160 if (null !== $this->languages) {
3161 return $this->languages;
3163 $languages = AcceptHeader::fromString($this->headers->get(
'Accept-Language'))->all();
3164 $this->languages = array();
3165 foreach (array_keys($languages) as $lang) {
3166 if (strstr($lang,
'-')) {
3167 $codes = explode(
'-', $lang);
3168 if (
'i' === $codes[0]) {
3169 if (count($codes) > 1) {
3173 for (
$i = 0, $max = count($codes);
$i < $max;
$i++) {
3175 $lang = strtolower($codes[0]);
3177 $lang .=
'_' . strtoupper($codes[
$i]);
3182 $this->languages[] = $lang;
3184 return $this->languages;
3188 if (null !== $this->charsets) {
3189 return $this->charsets;
3191 return $this->charsets = array_keys(AcceptHeader::fromString($this->headers->get(
'Accept-Charset'))->all());
3195 if (null !== $this->encodings) {
3196 return $this->encodings;
3198 return $this->encodings = array_keys(AcceptHeader::fromString($this->headers->get(
'Accept-Encoding'))->all());
3202 if (null !== $this->acceptableContentTypes) {
3203 return $this->acceptableContentTypes;
3205 return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get(
'Accept'))->all());
3209 return 'XMLHttpRequest' == $this->headers->get(
'X-Requested-With');
3214 if ($this->headers->has(
'X_ORIGINAL_URL')) {
3215 $requestUri = $this->headers->get(
'X_ORIGINAL_URL');
3216 $this->headers->remove(
'X_ORIGINAL_URL');
3217 $this->server->remove(
'HTTP_X_ORIGINAL_URL');
3218 $this->server->remove(
'UNENCODED_URL');
3219 $this->server->remove(
'IIS_WasUrlRewritten');
3220 } elseif ($this->headers->has(
'X_REWRITE_URL')) {
3221 $requestUri = $this->headers->get(
'X_REWRITE_URL');
3222 $this->headers->remove(
'X_REWRITE_URL');
3223 } elseif ($this->server->get(
'IIS_WasUrlRewritten') ==
'1' && $this->server->get(
'UNENCODED_URL') !=
'') {
3224 $requestUri = $this->server->get(
'UNENCODED_URL');
3225 $this->server->remove(
'UNENCODED_URL');
3226 $this->server->remove(
'IIS_WasUrlRewritten');
3227 } elseif ($this->server->has(
'REQUEST_URI')) {
3228 $requestUri = $this->server->get(
'REQUEST_URI');
3229 $schemeAndHttpHost = $this->getSchemeAndHttpHost();
3230 if (strpos($requestUri, $schemeAndHttpHost) === 0) {
3231 $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
3233 } elseif ($this->server->has(
'ORIG_PATH_INFO')) {
3234 $requestUri = $this->server->get(
'ORIG_PATH_INFO');
3235 if (
'' != $this->server->get(
'QUERY_STRING')) {
3236 $requestUri .=
'?' . $this->server->get(
'QUERY_STRING');
3238 $this->server->remove(
'ORIG_PATH_INFO');
3240 $this->server->set(
'REQUEST_URI', $requestUri);
3245 $filename = basename($this->server->get(
'SCRIPT_FILENAME'));
3246 if (basename($this->server->get(
'SCRIPT_NAME')) === $filename) {
3247 $baseUrl = $this->server->get(
'SCRIPT_NAME');
3248 } elseif (basename($this->server->get(
'PHP_SELF')) === $filename) {
3249 $baseUrl = $this->server->get(
'PHP_SELF');
3250 } elseif (basename($this->server->get(
'ORIG_SCRIPT_NAME')) === $filename) {
3251 $baseUrl = $this->server->get(
'ORIG_SCRIPT_NAME');
3253 $path = $this->server->get(
'PHP_SELF',
'');
3254 $file = $this->server->get(
'SCRIPT_FILENAME',
'');
3255 $segs = explode(
'/', trim($file,
'/'));
3256 $segs = array_reverse($segs);
3258 $last = count($segs);
3261 $seg = $segs[$index];
3262 $baseUrl =
'/' . $seg . $baseUrl;
3264 }
while ($last > $index &&
false !== ($pos = strpos(
$path, $baseUrl)) && 0 != $pos);
3266 $requestUri = $this->getRequestUri();
3267 if ($baseUrl &&
false !== ($prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl))) {
3270 if ($baseUrl &&
false !== ($prefix = $this->getUrlencodedPrefix($requestUri, dirname($baseUrl) .
'/'))) {
3271 return rtrim($prefix,
'/');
3273 $truncatedRequestUri = $requestUri;
3274 if (
false !== ($pos = strpos($requestUri,
'?'))) {
3275 $truncatedRequestUri = substr($requestUri, 0, $pos);
3277 $basename = basename($baseUrl);
3278 if (
empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) {
3281 if (strlen($requestUri) >= strlen($baseUrl) &&
false !== ($pos = strpos($requestUri, $baseUrl)) && $pos !== 0) {
3282 $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
3284 return rtrim($baseUrl,
'/');
3288 $filename = basename($this->server->get(
'SCRIPT_FILENAME'));
3289 $baseUrl = $this->getBaseUrl();
3290 if (
empty($baseUrl)) {
3293 if (basename($baseUrl) === $filename) {
3298 if (
'\\' === DIRECTORY_SEPARATOR) {
3305 $baseUrl = $this->getBaseUrl();
3306 if (null === ($requestUri = $this->getRequestUri())) {
3310 if ($pos = strpos($requestUri,
'?')) {
3311 $requestUri = substr($requestUri, 0, $pos);
3313 if (null !== $baseUrl &&
false === ($pathInfo = substr($requestUri, strlen($baseUrl)))) {
3315 } elseif (null === $baseUrl) {
3318 return (
string) $pathInfo;
3322 static::$formats = array(
'html' => array(
'text/html',
'application/xhtml+xml'),
'txt' => array(
'text/plain'),
'js' => array(
'application/javascript',
'application/x-javascript',
'text/javascript'),
'css' => array(
'text/css'),
'json' => array(
'application/json',
'application/x-json'),
'xml' => array(
'text/xml',
'application/xml',
'application/x-xml'),
'rdf' => array(
'application/rdf+xml'),
'atom' => array(
'application/atom+xml'),
'rss' => array(
'application/rss+xml'),
'form' => array(
'application/x-www-form-urlencoded'));
3324 private function setPhpDefaultLocale($locale)
3327 if (class_exists(
'Locale',
false)) {
3328 \Locale::setDefault($locale);
3330 }
catch (\Exception $e) {
3333 private function getUrlencodedPrefix($string, $prefix)
3335 if (0 !== strpos(rawurldecode($string), $prefix)) {
3338 $len = strlen($prefix);
3339 if (preg_match(sprintf(
'#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) {
3344 private static function createRequestFromFactory(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
3346 if (self::$requestFactory) {
3347 $request = call_user_func(self::$requestFactory, $query, $request, $attributes, $cookies, $files, $server, $content);
3348 if (!$request instanceof
Request) {
3349 throw new \LogicException(
'The Request factory must return an instance of Symfony\\Component\\HttpFoundation\\Request.');
3353 return new static($query, $request, $attributes, $cookies, $files, $server, $content);
3355 private function isFromTrustedProxy()
3357 return self::$trustedProxies && IpUtils::checkIp($this->server->get(
'REMOTE_ADDR'), self::$trustedProxies);
3367 $this->parameters = $parameters;
3371 return $this->parameters;
3375 return array_keys($this->parameters);
3377 public function replace(array $parameters = array())
3379 $this->parameters = $parameters;
3381 public function add(array $parameters = array())
3383 $this->parameters = array_replace($this->parameters, $parameters);
3385 public function get(
$path, $default = null, $deep =
false)
3387 if (!$deep ||
false === ($pos = strpos(
$path,
'['))) {
3388 return array_key_exists(
$path, $this->parameters) ? $this->parameters[
$path] : $default;
3390 $root = substr(
$path, 0, $pos);
3391 if (!array_key_exists($root, $this->parameters)) {
3394 $value = $this->parameters[$root];
3398 if (
'[' === $char) {
3399 if (null !== $currentKey) {
3400 throw new \InvalidArgumentException(sprintf(
'Malformed path. Unexpected "[" at position %d.',
$i));
3403 } elseif (
']' === $char) {
3404 if (null === $currentKey) {
3405 throw new \InvalidArgumentException(sprintf(
'Malformed path. Unexpected "]" at position %d.',
$i));
3407 if (!is_array($value) || !array_key_exists($currentKey, $value)) {
3410 $value = $value[$currentKey];
3413 if (null === $currentKey) {
3414 throw new \InvalidArgumentException(sprintf(
'Malformed path. Unexpected "%s" at position %d.', $char,
$i));
3416 $currentKey .= $char;
3419 if (null !== $currentKey) {
3420 throw new \InvalidArgumentException(sprintf(
'Malformed path. Path must end with "]".'));
3424 public function set($key, $value)
3426 $this->parameters[$key] = $value;
3430 return array_key_exists($key, $this->parameters);
3432 public function remove($key)
3434 unset($this->parameters[$key]);
3436 public function getAlpha($key, $default =
'', $deep =
false)
3438 return preg_replace(
'/[^[:alpha:]]/',
'', $this->
get($key, $default, $deep));
3440 public function getAlnum($key, $default =
'', $deep =
false)
3442 return preg_replace(
'/[^[:alnum:]]/',
'', $this->
get($key, $default, $deep));
3444 public function getDigits($key, $default =
'', $deep =
false)
3446 return str_replace(array(
'-',
'+'),
'', $this->
filter($key, $default, $deep, FILTER_SANITIZE_NUMBER_INT));
3448 public function getInt($key, $default = 0, $deep =
false)
3450 return (
int) $this->
get($key, $default, $deep);
3452 public function getBoolean($key, $default =
false, $deep =
false)
3454 return $this->
filter($key, $default, $deep, FILTER_VALIDATE_BOOLEAN);
3456 public function filter($key, $default = null, $deep =
false,
$filter = FILTER_DEFAULT, $options = array())
3458 $value = $this->
get($key, $default, $deep);
3459 if (!is_array($options) &&
$options) {
3460 $options = array(
'flags' => $options);
3462 if (is_array($value) && !isset($options[
'flags'])) {
3463 $options[
'flags'] = FILTER_REQUIRE_ARRAY;
3465 return filter_var($value,
$filter, $options);
3469 return new \ArrayIterator($this->parameters);
3473 return count($this->parameters);
3481 private static $fileKeys = array(
'error',
'name',
'size',
'tmp_name',
'type');
3484 $this->replace($parameters);
3488 $this->parameters = array();
3491 public function set($key, $value)
3493 if (!is_array($value) && !$value instanceof
UploadedFile) {
3494 throw new \InvalidArgumentException(
'An uploaded file must be an array or an instance of UploadedFile.');
3496 parent::set($key, $this->convertFileInformation($value));
3498 public function add(array $files = array())
3500 foreach ($files as $key => $file) {
3501 $this->
set($key, $file);
3509 $file = $this->fixPhpFilesArray($file);
3510 if (is_array($file)) {
3511 $keys = array_keys($file);
3513 if ($keys == self::$fileKeys) {
3514 if (UPLOAD_ERR_NO_FILE == $file[
'error']) {
3517 $file =
new UploadedFile($file[
'tmp_name'], $file[
'name'], $file[
'type'], $file[
'size'], $file[
'error']);
3520 $file = array_map(array($this,
'convertFileInformation'), $file);
3527 if (!is_array($data)) {
3530 $keys = array_keys($data);
3532 if (self::$fileKeys != $keys || !isset($data[
'name']) || !is_array($data[
'name'])) {
3536 foreach (self::$fileKeys as $k) {
3539 foreach ($data[
'name'] as $key => $name) {
3540 $files[$key] = $this->fixPhpFilesArray(array(
'error' => $data[
'error'][$key],
'name' => $name,
'type' => $data[
'type'][$key],
'tmp_name' => $data[
'tmp_name'][$key],
'size' => $data[
'size'][$key]));
3552 $contentHeaders = array(
'CONTENT_LENGTH' =>
true,
'CONTENT_MD5' =>
true,
'CONTENT_TYPE' =>
true);
3553 foreach ($this->parameters as $key => $value) {
3554 if (0 === strpos($key,
'HTTP_')) {
3555 $headers[substr($key, 5)] = $value;
3556 } elseif (isset($contentHeaders[$key])) {
3557 $headers[$key] = $value;
3560 if (isset($this->parameters[
'PHP_AUTH_USER'])) {
3561 $headers[
'PHP_AUTH_USER'] = $this->parameters[
'PHP_AUTH_USER'];
3562 $headers[
'PHP_AUTH_PW'] = isset($this->parameters[
'PHP_AUTH_PW']) ? $this->parameters[
'PHP_AUTH_PW'] :
'';
3564 $authorizationHeader = null;
3565 if (isset($this->parameters[
'HTTP_AUTHORIZATION'])) {
3566 $authorizationHeader = $this->parameters[
'HTTP_AUTHORIZATION'];
3567 } elseif (isset($this->parameters[
'REDIRECT_HTTP_AUTHORIZATION'])) {
3568 $authorizationHeader = $this->parameters[
'REDIRECT_HTTP_AUTHORIZATION'];
3570 if (null !== $authorizationHeader) {
3571 if (0 === stripos($authorizationHeader,
'basic ')) {
3572 $exploded = explode(
':', base64_decode(substr($authorizationHeader, 6)), 2);
3573 if (count($exploded) == 2) {
3574 list($headers[
'PHP_AUTH_USER'], $headers[
'PHP_AUTH_PW']) = $exploded;
3576 } elseif (
empty($this->parameters[
'PHP_AUTH_DIGEST']) && 0 === stripos($authorizationHeader,
'digest ')) {
3577 $headers[
'PHP_AUTH_DIGEST'] = $authorizationHeader;
3578 $this->parameters[
'PHP_AUTH_DIGEST'] = $authorizationHeader;
3582 if (isset($headers[
'PHP_AUTH_USER'])) {
3583 $headers[
'AUTHORIZATION'] =
'Basic ' . base64_encode($headers[
'PHP_AUTH_USER'] .
':' . $headers[
'PHP_AUTH_PW']);
3584 } elseif (isset($headers[
'PHP_AUTH_DIGEST'])) {
3585 $headers[
'AUTHORIZATION'] = $headers[
'PHP_AUTH_DIGEST'];
3594 protected $headers = array();
3595 protected $cacheControl = array();
3598 foreach ($headers as $key => $values) {
3599 $this->
set($key, $values);
3604 if (!$this->headers) {
3607 $max =
max(array_map(
'strlen', array_keys($this->headers))) + 1;
3609 ksort($this->headers);
3610 foreach ($this->headers as $name => $values) {
3611 $name = implode(
'-', array_map(
'ucfirst', explode(
'-', $name)));
3612 foreach ($values as $value) {
3613 $content .= sprintf(
"%-{$max}s %s\r\n", $name .
':', $value);
3620 return $this->headers;
3624 return array_keys($this->headers);
3628 $this->headers = array();
3629 $this->add($headers);
3631 public function add(array $headers)
3633 foreach ($headers as $key => $values) {
3634 $this->
set($key, $values);
3637 public function get($key, $default = null, $first =
true)
3639 $key = strtr(strtolower($key),
'_',
'-');
3640 if (!array_key_exists($key, $this->headers)) {
3641 if (null === $default) {
3642 return $first ? null : array();
3644 return $first ? $default : array($default);
3647 return count($this->headers[$key]) ? $this->headers[$key][0] : $default;
3649 return $this->headers[$key];
3651 public function set($key, $values, $replace =
true)
3653 $key = strtr(strtolower($key),
'_',
'-');
3654 $values = array_values((array) $values);
3655 if (
true === $replace || !isset($this->headers[$key])) {
3656 $this->headers[$key] = $values;
3658 $this->headers[$key] = array_merge($this->headers[$key], $values);
3660 if (
'cache-control' === $key) {
3661 $this->cacheControl = $this->parseCacheControl($values[0]);
3666 return array_key_exists(strtr(strtolower($key),
'_',
'-'), $this->headers);
3670 return in_array($value, $this->
get($key, null,
false));
3672 public function remove($key)
3674 $key = strtr(strtolower($key),
'_',
'-');
3675 unset($this->headers[$key]);
3676 if (
'cache-control' === $key) {
3677 $this->cacheControl = array();
3682 if (null === ($value = $this->
get($key))) {
3685 if (
false === ($date = \DateTime::createFromFormat(DATE_RFC2822, $value))) {
3686 throw new \RuntimeException(sprintf(
'The %s HTTP header is not parseable (%s).', $key, $value));
3692 $this->cacheControl[$key] = $value;
3693 $this->
set(
'Cache-Control', $this->getCacheControlHeader());
3697 return array_key_exists($key, $this->cacheControl);
3701 return array_key_exists($key, $this->cacheControl) ? $this->cacheControl[$key] : null;
3705 unset($this->cacheControl[$key]);
3706 $this->
set(
'Cache-Control', $this->getCacheControlHeader());
3710 return new \ArrayIterator($this->headers);
3714 return count($this->headers);
3719 ksort($this->cacheControl);
3720 foreach ($this->cacheControl as $key => $value) {
3721 if (
true === $value) {
3724 if (preg_match(
'#[^a-zA-Z0-9._-]#', $value)) {
3725 $value =
'"' . $value .
'"';
3727 $parts[] =
"{$key}={$value}";
3730 return implode(
', ', $parts);
3734 $cacheControl = array();
3735 preg_match_all(
'#([a-zA-Z][a-zA-Z_-]*)\\s*(?:=(?:"([^"]*)"|([^ \\t",;]*)))?#', $header, $matches, PREG_SET_ORDER);
3736 foreach ($matches as $match) {
3737 $cacheControl[strtolower($match[1])] = isset($match[3]) ? $match[3] : (isset($match[2]) ? $match[2] :
true);
3739 return $cacheControl;
3747 public function start();
3748 public function getId();
3749 public function setId($id);
3750 public function getName();
3751 public function setName($name);
3752 public function invalidate($lifetime = null);
3753 public function migrate($destroy =
false, $lifetime = null);
3754 public function save();
3755 public function has($name);
3756 public function get($name, $default = null);
3757 public function set($name, $value);
3758 public function all();
3759 public function replace(array $attributes);
3760 public function remove($name);
3761 public function clear();
3762 public function isStarted();
3764 public function getBag($name);
3765 public function getMetadataBag();
3771 public function getName();
3772 public function initialize(array &$array);
3773 public function getStorageKey();
3774 public function clear();
3781 public function has($name);
3782 public function get($name, $default = null);
3783 public function set($name, $value);
3784 public function all();
3785 public function replace(array $attributes);
3786 public function remove($name);
3792 private $name =
'attributes';
3793 private $storageKey;
3794 protected $attributes = array();
3797 $this->storageKey = $storageKey;
3805 $this->
name = $name;
3809 $this->attributes =& $attributes;
3813 return $this->storageKey;
3817 return array_key_exists($name, $this->attributes);
3819 public function get($name, $default = null)
3821 return array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default;
3823 public function set($name, $value)
3825 $this->attributes[$name] = $value;
3829 return $this->attributes;
3833 $this->attributes = array();
3834 foreach ($attributes as $key => $value) {
3835 $this->
set($key, $value);
3838 public function remove($name)
3841 if (array_key_exists($name, $this->attributes)) {
3842 $retval = $this->attributes[$name];
3843 unset($this->attributes[$name]);
3849 $return = $this->attributes;
3850 $this->attributes = array();
3855 return new \ArrayIterator($this->attributes);
3859 return count($this->attributes);
3867 const CREATED =
'c';
3868 const UPDATED =
'u';
3869 const LIFETIME =
'l';
3870 private $name =
'__metadata';
3871 private $storageKey;
3872 protected $meta = array(self::CREATED => 0, self::UPDATED => 0, self::LIFETIME => 0);
3874 private $updateThreshold;
3875 public function __construct($storageKey =
'_sf2_meta', $updateThreshold = 0)
3877 $this->storageKey = $storageKey;
3878 $this->updateThreshold = $updateThreshold;
3882 $this->meta =& $array;
3883 if (isset($array[self::CREATED])) {
3884 $this->lastUsed = $this->meta[self::UPDATED];
3885 $timeStamp = time();
3886 if ($timeStamp - $array[self::UPDATED] >= $this->updateThreshold) {
3887 $this->meta[self::UPDATED] = $timeStamp;
3890 $this->stampCreated();
3895 return $this->meta[self::LIFETIME];
3899 $this->stampCreated($lifetime);
3903 return $this->storageKey;
3907 return $this->meta[self::CREATED];
3911 return $this->lastUsed;
3922 $this->
name = $name;
3924 private function stampCreated($lifetime = null)
3926 $timeStamp = time();
3927 $this->meta[self::CREATED] = $this->meta[self::UPDATED] = $this->lastUsed = $timeStamp;
3928 $this->meta[self::LIFETIME] = null === $lifetime ? ini_get(
'session.cookie_lifetime') : $lifetime;
3936 private $quality = 1.0;
3938 private $attributes = array();
3941 $this->value = $value;
3942 foreach ($attributes as $name => $value) {
3943 $this->setAttribute($name, $value);
3948 $bits = preg_split(
'/\\s*(?:;*("[^"]+");*|;*(\'[^\']+\');*|;+)\\s*/', $itemValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
3949 $value = array_shift($bits);
3950 $attributes = array();
3951 $lastNullAttribute = null;
3952 foreach ($bits as $bit) {
3953 if ((
$start = substr($bit, 0, 1)) === ($end = substr($bit, -1)) && (
$start ===
'"' ||
$start ===
'\'')) {
3954 $attributes[$lastNullAttribute] = substr($bit, 1, -1);
3955 } elseif (
'=' === $end) {
3956 $lastNullAttribute = $bit = substr($bit, 0, -1);
3957 $attributes[$bit] = null;
3959 $parts = explode(
'=', $bit);
3960 $attributes[$parts[0]] = isset($parts[1]) && strlen($parts[1]) > 0 ? $parts[1] :
'';
3963 return new self((
$start = substr($value, 0, 1)) === ($end = substr($value, -1)) && (
$start ===
'"' ||
$start ===
'\'') ? substr($value, 1, -1) : $value, $attributes);
3967 $string = $this->value . ($this->quality < 1 ?
';q=' . $this->quality :
'');
3968 if (count($this->attributes) > 0) {
3969 $string .=
';' . implode(
';', array_map(
function ($name, $value) {
3970 return sprintf(preg_match(
'/[,;=]/', $value) ?
'%s="%s"' :
'%s=%s', $name, $value);
3971 }, array_keys($this->attributes), $this->attributes));
3977 $this->value = $value;
3982 return $this->value;
3986 $this->quality = $quality;
3991 return $this->quality;
3995 $this->index = $index;
4000 return $this->index;
4004 return isset($this->attributes[$name]);
4008 return isset($this->attributes[$name]) ? $this->attributes[$name] : $default;
4012 return $this->attributes;
4016 if (
'q' === $name) {
4017 $this->quality = (double) $value;
4019 $this->attributes[$name] = (string) $value;
4028 private $items = array();
4029 private $sorted =
true;
4032 foreach ($items as $item) {
4039 return new self(array_map(
function ($itemValue) use(&$index) {
4040 $item = AcceptHeaderItem::fromString($itemValue);
4041 $item->setIndex($index++);
4043 }, preg_split(
'/\\s*(?:,*("[^"]+"),*|,*(\'[^\']+\'),*|,+)\\s*/', $headerValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)));
4047 return implode(
',', $this->items);
4051 return isset($this->items[$value]);
4053 public function get($value)
4055 return isset($this->items[$value]) ? $this->items[$value] : null;
4059 $this->items[$item->
getValue()] = $item;
4060 $this->sorted =
false;
4066 return $this->items;
4070 return new self(array_filter($this->items,
function (
AcceptHeaderItem $item) use($pattern) {
4071 return preg_match($pattern, $item->
getValue());
4077 return !
empty($this->items) ? reset($this->items) : null;
4079 private function sort()
4081 if (!$this->sorted) {
4082 uasort($this->items,
function (
$a,
$b) {
4083 $qA =
$a->getQuality();
4084 $qB =
$b->getQuality();
4086 return $a->getIndex() >
$b->getIndex() ? 1 : -1;
4088 return $qA > $qB ? -1 : 1;
4090 $this->sorted =
true;
4104 private $caughtBuffer;
4105 private $caughtLength;
4106 private $fileLinkFormat;
4107 public function __construct($debug =
true, $charset = null, $fileLinkFormat = null)
4109 if (
false !== strpos($charset,
'%') xor
false === strpos($fileLinkFormat,
'%')) {
4110 $pivot = $fileLinkFormat;
4111 $fileLinkFormat = $charset;
4114 $this->debug = $debug;
4115 $this->charset = $charset ?: ini_get(
'default_charset') ?:
'UTF-8';
4116 $this->fileLinkFormat = $fileLinkFormat ?: ini_get(
'xdebug.file_link_format') ?: get_cfg_var(
'xdebug.file_link_format');
4118 public static function register($debug =
true, $charset = null, $fileLinkFormat = null)
4120 $handler =
new static($debug, $charset, $fileLinkFormat);
4121 $prev = set_exception_handler(array($handler,
'handle'));
4122 if (is_array($prev) && $prev[0] instanceof
ErrorHandler) {
4123 restore_exception_handler();
4124 $prev[0]->setExceptionHandler(array($handler,
'handle'));
4130 if (null !== $handler && !is_callable($handler)) {
4131 throw new \LogicException(
'The exception handler must be a valid PHP callable.');
4133 $old = $this->handler;
4134 $this->handler = $handler;
4139 $old = $this->fileLinkFormat;
4140 $this->fileLinkFormat = $format;
4143 public function handle(\Exception $exception)
4146 $this->failSafeHandle($exception);
4149 $caughtLength = $this->caughtLength = 0;
4150 ob_start(array($this,
'catchOutput'));
4151 $this->failSafeHandle($exception);
4152 while (null === $this->caughtBuffer && ob_end_flush()) {
4154 if (isset($this->caughtBuffer[0])) {
4155 ob_start(array($this,
'cleanOutput'));
4156 echo $this->caughtBuffer;
4157 $caughtLength = ob_get_length();
4159 $this->caughtBuffer = null;
4161 call_user_func($this->handler, $exception);
4162 $this->caughtLength = $caughtLength;
4163 }
catch (\Exception $e) {
4164 if (!$caughtLength) {
4169 private function failSafeHandle(\Exception $exception)
4171 if (class_exists(
'Symfony\\Component\\HttpFoundation\\Response',
false)) {
4172 $response = $this->createResponse($exception);
4176 $this->sendPhpResponse($exception);
4182 $exception = FlattenException::create($exception);
4184 if (!headers_sent()) {
4185 header(sprintf(
'HTTP/1.0 %s', $exception->getStatusCode()));
4186 foreach ($exception->getHeaders() as $name => $value) {
4187 header($name .
': ' . $value,
false);
4189 header(
'Content-Type: text/html; charset=' . $this->charset);
4191 echo $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
4196 $exception = FlattenException::create($exception);
4198 return Response::create($this->decorate($this->getContent($exception), $this->getStylesheet($exception)), $exception->getStatusCode(), $exception->getHeaders())->setCharset($this->charset);
4204 $title =
'Sorry, the page you are looking for could not be found.';
4207 $title =
'Whoops, looks like something went wrong.';
4214 foreach ($exception->
toArray() as $position => $e) {
4215 $ind =
$count - $position + 1;
4216 $class = $this->formatClass($e[
'class']);
4217 $message = nl2br($this->escapeHtml($e[
'message']));
4218 $content .= sprintf(
' <h2 class="block_exception clear_fix">
4219 <span class="exception_counter">%d/%d</span>
4220 <span class="exception_title">%s%s:</span>
4221 <span class="exception_message">%s</span>
4224 <ol class="traces list_exception">', $ind, $total, $class, $this->formatPath($e[
'trace'][0][
'file'], $e[
'trace'][0][
'line']), $message);
4225 foreach ($e[
'trace'] as $trace) {
4226 $content .=
' <li>';
4227 if ($trace[
'function']) {
4228 $content .= sprintf(
'at %s%s%s(%s)', $this->formatClass($trace[
'class']), $trace[
'type'], $trace[
'function'], $this->formatArgs($trace[
'args']));
4230 if (isset($trace[
'file']) && isset($trace[
'line'])) {
4231 $content .= $this->formatPath($trace[
'file'], $trace[
'line']);
4240 }
catch (\Exception $e) {
4242 $title = sprintf(
'Exception thrown when handling an exception (%s: %s)', get_class($e), $this->escapeHtml($e->getMessage()));
4244 $title =
'Whoops, looks like something went wrong.';
4248 return " <div id=\"sf-resetcontent\" class=\"sf-reset\">\n <h1>{$title}</h1>\n {$content}\n </div>";
4252 return ' .sf-reset { font: 11px Verdana, Arial, sans-serif; color: #333 }
4253 .sf-reset .clear { clear:both; height:0; font-size:0; line-height:0; }
4254 .sf-reset .clear_fix:after { display:block; height:0; clear:both; visibility:hidden; }
4255 .sf-reset .clear_fix { display:inline-block; }
4256 .sf-reset * html .clear_fix { height:1%; }
4257 .sf-reset .clear_fix { display:block; }
4258 .sf-reset, .sf-reset .block { margin: auto }
4259 .sf-reset abbr { border-bottom: 1px dotted #000; cursor: help; }
4260 .sf-reset p { font-size:14px; line-height:20px; color:#868686; padding-bottom:20px }
4261 .sf-reset strong { font-weight:bold; }
4262 .sf-reset a { color:#6c6159; cursor: default; }
4263 .sf-reset a img { border:none; }
4264 .sf-reset a:hover { text-decoration:underline; }
4265 .sf-reset em { font-style:italic; }
4266 .sf-reset h1, .sf-reset h2 { font: 20px Georgia, "Times New Roman", Times, serif }
4267 .sf-reset .exception_counter { background-color: #fff; color: #333; padding: 6px; float: left; margin-right: 10px; float: left; display: block; }
4268 .sf-reset .exception_title { margin-left: 3em; margin-bottom: 0.7em; display: block; }
4269 .sf-reset .exception_message { margin-left: 3em; display: block; }
4270 .sf-reset .traces li { font-size:12px; padding: 2px 4px; list-style-type:decimal; margin-left:20px; }
4271 .sf-reset .block { background-color:#FFFFFF; padding:10px 28px; margin-bottom:20px;
4272 -webkit-border-bottom-right-radius: 16px;
4273 -webkit-border-bottom-left-radius: 16px;
4274 -moz-border-radius-bottomright: 16px;
4275 -moz-border-radius-bottomleft: 16px;
4276 border-bottom-right-radius: 16px;
4277 border-bottom-left-radius: 16px;
4278 border-bottom:1px solid #ccc;
4279 border-right:1px solid #ccc;
4280 border-left:1px solid #ccc;
4282 .sf-reset .block_exception { background-color:#ddd; color: #333; padding:20px;
4283 -webkit-border-top-left-radius: 16px;
4284 -webkit-border-top-right-radius: 16px;
4285 -moz-border-radius-topleft: 16px;
4286 -moz-border-radius-topright: 16px;
4287 border-top-left-radius: 16px;
4288 border-top-right-radius: 16px;
4289 border-top:1px solid #ccc;
4290 border-right:1px solid #ccc;
4291 border-left:1px solid #ccc;
4293 word-wrap: break-word;
4295 .sf-reset a { background:none; color:#868686; text-decoration:none; }
4296 .sf-reset a:hover { background:none; color:#313131; text-decoration:underline; }
4297 .sf-reset ol { padding: 10px 0; }
4298 .sf-reset h1 { background-color:#FFFFFF; padding: 15px 28px; margin-bottom: 20px;
4299 -webkit-border-radius: 10px;
4300 -moz-border-radius: 10px;
4301 border-radius: 10px;
4302 border: 1px solid #ccc;
4305 private function decorate($content, $css)
4307 return "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"{$this->charset}\" />\n <meta name=\"robots\" content=\"noindex,nofollow\" />\n <style>\n /* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html */\n html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:text-top;}sub{vertical-align:text-bottom;}input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}input,textarea,select{*font-size:100%;}legend{color:#000;}\n\n html { background: #eee; padding: 10px }\n img { border: 0; }\n #sf-resetcontent { width:970px; margin:0 auto; }\n {$css}\n </style>\n </head>\n <body>\n {$content}\n </body>\n</html>";
4309 private function formatClass($class)
4311 $parts = explode(
'\\', $class);
4312 return sprintf(
'<abbr title="%s">%s</abbr>', $class, array_pop($parts));
4314 private function formatPath(
$path, $line)
4317 $file = preg_match(
'#[^/\\\\]*$#',
$path, $file) ? $file[0] :
$path;
4318 if ($linkFormat = $this->fileLinkFormat) {
4319 $link = str_replace(array(
'%f',
'%l'), array(
$path, $line), $linkFormat);
4320 return sprintf(
' in <a href="%s" title="Go to source">%s line %d</a>', $link, $file, $line);
4322 return sprintf(
' in <a title="%s line %3$d" ondblclick="var f=this.innerHTML;this.innerHTML=this.title;this.title=f;">%s line %d</a>',
$path, $file, $line);
4324 private function formatArgs(array $args)
4327 foreach ($args as $key => $item) {
4328 if (
'object' === $item[0]) {
4329 $formattedValue = sprintf(
'<em>object</em>(%s)', $this->formatClass($item[1]));
4330 } elseif (
'array' === $item[0]) {
4331 $formattedValue = sprintf(
'<em>array</em>(%s)', is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]);
4332 } elseif (
'string' === $item[0]) {
4333 $formattedValue = sprintf(
'\'%s\
'', $this->escapeHtml($item[1]));
4334 } elseif (
'null' === $item[0]) {
4335 $formattedValue =
'<em>null</em>';
4336 } elseif (
'boolean' === $item[0]) {
4337 $formattedValue =
'<em>' . strtolower(var_export($item[1],
true)) .
'</em>';
4338 } elseif (
'resource' === $item[0]) {
4339 $formattedValue =
'<em>resource</em>';
4341 $formattedValue = str_replace(
'
4342 ',
'', var_export($this->escapeHtml((
string) $item[1]),
true));
4344 $result[] = is_int($key) ? $formattedValue : sprintf(
'\'%s\
' => %s', $key, $formattedValue);
4346 return implode(
', ', $result);
4350 if (!preg_match(
'//u', $str) && function_exists(
'iconv')) {
4351 set_error_handler(
'var_dump', 0);
4352 $charset = ini_get(
'default_charset');
4353 if (
'UTF-8' === $charset || $str !== @iconv($charset, $charset, $str)) {
4354 $charset =
'CP1252';
4356 restore_error_handler();
4357 $str = iconv($charset,
'UTF-8', $str);
4359 return htmlspecialchars($str, ENT_QUOTES | (PHP_VERSION_ID >= 50400 ? ENT_SUBSTITUTE : 0),
'UTF-8');
4361 private function escapeHtml($str)
4363 return htmlspecialchars($str, ENT_QUOTES | (PHP_VERSION_ID >= 50400 ? ENT_SUBSTITUTE : 0), $this->charset);
4367 $this->caughtBuffer = $buffer;
4372 if ($this->caughtLength) {
4373 $cleanBuffer = substr_replace($buffer,
'', 0, $this->caughtLength);
4374 if (isset($cleanBuffer[0])) {
4375 $buffer = $cleanBuffer;
4387 protected $defer =
false;
4388 protected static $publishes = array();
4389 protected static $publishGroups = array();
4394 public abstract function register();
4397 $config = $this->app[
'config']->get($key, array());
4398 $this->app[
'config']->set($key, array_merge(require
$path, $config));
4402 if (is_dir($appPath = $this->app->basePath() .
'/resources/views/vendor/' . $namespace)) {
4403 $this->app[
'view']->addNamespace($namespace, $appPath);
4405 $this->app[
'view']->addNamespace($namespace,
$path);
4409 $this->app[
'translator']->addNamespace($namespace,
$path);
4413 $class = get_class($this);
4414 if (!array_key_exists($class, static::$publishes)) {
4415 static::$publishes[$class] = array();
4417 static::$publishes[$class] = array_merge(static::$publishes[$class], $paths);
4419 static::$publishGroups[$group] = $paths;
4424 if ($group && array_key_exists($group, static::$publishGroups)) {
4425 return static::$publishGroups[$group];
4427 if ($provider && array_key_exists($provider, static::$publishes)) {
4428 return static::$publishes[$provider];
4430 if ($group || $provider) {
4434 foreach (static::$publishes as $class => $publish) {
4435 $paths = array_merge($paths, $publish);
4441 $commands = is_array($commands) ? $commands : func_get_args();
4442 $events = $this->app[
'events'];
4443 $events->listen(
'artisan.start',
function ($artisan) use($commands) {
4444 $artisan->resolveCommands($commands);
4457 return $this->defer;
4465 if ($method ==
'boot') {
4468 throw new BadMethodCallException(
"Call to undefined method [{$method}]");
4475 protected $providers = array();
4476 protected $instances = array();
4477 public function register()
4479 $this->instances = array();
4480 foreach ($this->providers as $provider) {
4481 $this->instances[] = $this->app->register($provider);
4486 $provides = array();
4487 foreach ($this->providers as $provider) {
4488 $instance = $this->app->resolveProviderClass($provider);
4489 $provides = array_merge($provides, $instance->provides());
4499 public function register()
4501 $this->registerRouter();
4502 $this->registerUrlGenerator();
4503 $this->registerRedirector();
4504 $this->registerResponseFactory();
4508 $this->app[
'router'] = $this->app->share(
function (
$app) {
4514 $this->app[
'url'] = $this->app->share(
function (
$app) {
4515 $routes =
$app[
'router']->getRoutes();
4516 $app->instance(
'routes', $routes);
4517 $url =
new UrlGenerator($routes,
$app->rebinding(
'request', $this->requestRebinder()));
4518 $url->setSessionResolver(
function () {
4519 return $this->app[
'session'];
4521 $app->rebinding(
'routes',
function (
$app, $routes) {
4522 $app[
'url']->setRoutes($routes);
4529 return function (
$app, $request) {
4530 $app[
'url']->setRequest($request);
4535 $this->app[
'redirect'] = $this->app->share(
function (
$app) {
4537 if (isset(
$app[
'session.store'])) {
4538 $redirector->setSession(
$app[
'session.store']);
4545 $this->app->singleton(
'Illuminate\\Contracts\\Routing\\ResponseFactory',
function (
$app) {
4555 public function register()
4557 $this->app->singleton(
'illuminate.route.dispatcher',
function (
$app) {
4567 public function register()
4569 $this->app->singleton(
'events',
function (
$app) {
4571 return $app->make(
'Illuminate\\Contracts\\Queue\\Queue');
4582 public function register()
4584 $this->registerValidationResolverHook();
4585 $this->registerPresenceVerifier();
4586 $this->registerValidationFactory();
4596 $this->app->singleton(
'validator',
function (
$app) {
4598 if (isset(
$app[
'validation.presence'])) {
4599 $validator->setPresenceVerifier(
$app[
'validation.presence']);
4606 $this->app->singleton(
'validation.presence',
function (
$app) {
4619 public function validate(
Request $request, array $rules, array $messages = array())
4621 $validator = $this->getValidationFactory()->make($request->
all(), $rules, $messages);
4622 if ($validator->fails()) {
4623 $this->throwValidationException($request, $validator);
4626 protected function throwValidationException(
Request $request, $validator)
4628 throw new HttpResponseException($this->buildFailedValidationResponse($request, $this->formatValidationErrors($validator)));
4630 protected function buildFailedValidationResponse(
Request $request, array $errors)
4635 return redirect()->to($this->getRedirectUrl())->withInput($request->
input())->withErrors($errors, $this->errorBag());
4637 protected function formatValidationErrors(
Validator $validator)
4639 return $validator->
errors()->getMessages();
4641 protected function getRedirectUrl()
4643 return app(
'Illuminate\\Routing\\UrlGenerator')->previous();
4645 protected function getValidationFactory()
4647 return app(
'Illuminate\\Contracts\\Validation\\Factory');
4649 protected function errorBag()
4660 public function validate()
4662 $instance = $this->getValidatorInstance();
4663 if (!$this->passesAuthorization()) {
4664 $this->failedAuthorization();
4665 } elseif (!$instance->passes()) {
4666 $this->failedValidation($instance);
4669 protected function getValidatorInstance()
4671 return $this->validator();
4673 protected function failedValidation(
Validator $validator)
4677 protected function passesAuthorization()
4679 if (method_exists($this,
'authorize')) {
4680 return $this->authorize();
4684 protected function failedAuthorization()
4708 protected $errorBag =
'default';
4709 protected $dontFlash = array(
'password',
'password_confirmation');
4712 $factory = $this->container->make(
'Illuminate\\Validation\\Factory');
4713 if (method_exists($this,
'validator')) {
4714 return $this->container->call(array($this,
'validator'), compact(
'factory'));
4716 return $factory->make($this->all(), $this->container->call(array($this,
'rules')), $this->messages(), $this->attributes());
4724 if (method_exists($this,
'authorize')) {
4725 return $this->container->call(array($this,
'authorize'));
4735 if ($this->ajax() || $this->wantsJson()) {
4738 return $this->redirector->to($this->getRedirectUrl())->withInput($this->except($this->dontFlash))->withErrors($errors, $this->errorBag);
4742 return new Response(
'Forbidden', 403);
4746 return $validator->
errors()->getMessages();
4750 $url = $this->redirector->getUrlGenerator();
4751 if ($this->redirect) {
4752 return $url->to($this->redirect);
4753 } elseif ($this->redirectRoute) {
4754 return $url->route($this->redirectRoute);
4755 } elseif ($this->redirectAction) {
4756 return $url->action($this->redirectAction);
4758 return $url->previous();
4762 $this->redirector = $redirector;
4784 protected function dispatch($command)
4786 return app(
'Illuminate\\Contracts\\Bus\\Dispatcher')->dispatch($command);
4788 protected function dispatchFromArray($command, array $array)
4790 return app(
'Illuminate\\Contracts\\Bus\\Dispatcher')->dispatchFromArray($command, $array);
4792 protected function dispatchFrom($command, ArrayAccess $source, $extras = array())
4794 return app(
'Illuminate\\Contracts\\Bus\\Dispatcher')->dispatchFrom($command, $source, $extras);
4802 protected $providers = array(
'Illuminate\\Foundation\\Providers\\FormRequestServiceProvider');
4811 public function register()
4816 $this->app[
'events']->listen(
'router.matched',
function () {
4818 $this->initializeRequest($request,
$app[
'request']);
4825 $files = $current->files->all();
4826 $files = is_array($files) ? array_filter($files) : $files;
4827 $form->
initialize($current->query->all(), $current->request->all(), $current->attributes->all(), $current->cookies->all(), $files, $current->server->all(), $current->
getContent());
4840 public function register()
4842 $this->registerAuthenticator();
4843 $this->registerUserResolver();
4844 $this->registerRequestRebindHandler();
4848 $this->app->singleton(
'auth',
function (
$app) {
4849 $app[
'auth.loaded'] =
true;
4852 $this->app->singleton(
'auth.driver',
function (
$app) {
4853 return $app[
'auth']->driver();
4858 $this->app->bind(
'Illuminate\\Contracts\\Auth\\Authenticatable',
function (
$app) {
4859 return $app[
'auth']->user();
4864 $this->app->rebinding(
'request',
function (
$app, $request) {
4865 $request->setUserResolver(
function () use(
$app) {
4866 return $app[
'auth']->user();
4876 public function register()
4878 Paginator::currentPathResolver(
function () {
4879 return $this->app[
'request']->url();
4881 Paginator::currentPageResolver(
function () {
4882 return $this->app[
'request']->input(
'page');
4895 $this->setRootControllerNamespace();
4896 if ($this->app->routesAreCached()) {
4897 $this->loadCachedRoutes();
4899 $this->loadRoutes();
4904 if (is_null($this->
namespace)) {
4907 $this->app[
'Illuminate\\Contracts\\Routing\\UrlGenerator']->setRootControllerNamespace($this->
namespace);
4911 $this->app->booted(
function () {
4912 require $this->app->getCachedRoutesPath();
4917 $this->app->call(array($this,
'map'));
4921 $router = $this->app[
'Illuminate\\Routing\\Router'];
4922 if (is_null($this->
namespace)) {
4923 return require
$path;
4925 $router->group(array(
'namespace' => $this->
namespace),
function ($router) use(
$path) {
4929 public function register()
4934 return call_user_func_array(array($this->app[
'router'], $method), $parameters);
4943 protected $listen = array();
4944 protected $subscribe = array();
4945 public function boot(DispatcherContract $events)
4947 foreach ($this->listen as $event => $listeners) {
4948 foreach ($listeners as $listener) {
4949 $events->listen($event, $listener);
4952 foreach ($this->subscribe as $subscriber) {
4953 $events->subscribe($subscriber);
4956 public function register()
4961 return $this->listen;
4969 protected $defer =
true;
4970 public function register()
4972 $this->app->singleton(
'hash',
function () {
4978 return array(
'hash');
4983 use RuntimeException;
4987 protected $rounds = 10;
4988 public function make($value, array $options = array())
4990 $cost = isset($options[
'rounds']) ? $options[
'rounds'] : $this->rounds;
4991 $hash = password_hash($value, PASSWORD_BCRYPT, array(
'cost' => $cost));
4992 if (
$hash ===
false) {
4993 throw new RuntimeException(
'Bcrypt hashing not supported.');
4997 public function check($value, $hashedValue, array $options = array())
4999 return password_verify($value, $hashedValue);
5003 $cost = isset($options[
'rounds']) ? $options[
'rounds'] : $this->rounds;
5004 return password_needs_rehash($hashedValue, PASSWORD_BCRYPT, array(
'cost' => $cost));
5008 $this->rounds = (int) $rounds;
5016 public function url($page);
5017 public function appends($key, $value = null);
5018 public function fragment($fragment = null);
5019 public function nextPageUrl();
5020 public function previousPageUrl();
5021 public function items();
5022 public function firstItem();
5023 public function lastItem();
5024 public function perPage();
5025 public function currentPage();
5026 public function hasPages();
5027 public function hasMorePages();
5041 protected $query = array();
5042 protected $fragment = null;
5043 protected $pageName =
'page';
5049 return $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !==
false;
5054 for ($page =
$start; $page <= $end; $page++) {
5055 $urls[$page] = $this->
url($page);
5064 $parameters = array($this->pageName => $page);
5065 if (count($this->query) > 0) {
5066 $parameters = array_merge($this->query, $parameters);
5068 return $this->
path .
'?' . http_build_query($parameters, null,
'&') . $this->buildFragment();
5072 if ($this->currentPage() > 1) {
5073 return $this->
url($this->currentPage() - 1);
5078 if (is_null($fragment)) {
5079 return $this->fragment;
5081 $this->fragment = $fragment;
5086 if (is_array($key)) {
5087 return $this->appendArray($key);
5089 return $this->addQuery($key, $value);
5093 foreach ($keys as $key => $value) {
5094 $this->addQuery($key, $value);
5100 if ($key !== $this->pageName) {
5101 $this->query[$key] = $value;
5107 return $this->fragment ?
'#' . $this->fragment :
'';
5111 return $this->items->all();
5115 return ($this->currentPage - 1) * $this->perPage + 1;
5119 return $this->firstItem() + $this->count() - 1;
5123 return $this->perPage;
5127 return $this->currentPage;
5131 return !($this->currentPage() == 1 && !$this->hasMorePages());
5135 if (isset(static::$currentPathResolver)) {
5136 return call_user_func(static::$currentPathResolver);
5142 static::$currentPathResolver = $resolver;
5146 if (isset(static::$currentPageResolver)) {
5147 return call_user_func(static::$currentPageResolver);
5153 static::$currentPageResolver = $resolver;
5157 static::$presenterResolver = $resolver;
5161 $this->pageName = $name;
5171 return new ArrayIterator($this->items->all());
5175 return $this->items->isEmpty();
5179 return $this->items->count();
5183 return $this->items;
5187 return $this->items->has($key);
5191 return $this->items->get($key);
5195 $this->items->put($key, $value);
5199 $this->items->forget($key);
5203 return call_user_func_array(array($this->getCollection(), $method), $parameters);
5223 public function __construct($items, $perPage, $currentPage = null, array $options = array())
5225 foreach ($options as $key => $value) {
5226 $this->{$key} = $value;
5228 $this->perPage = $perPage;
5229 $this->currentPage = $this->setCurrentPage($currentPage);
5231 $this->items = $items instanceof
Collection ? $items : Collection::make($items);
5232 $this->checkForMorePages();
5236 $currentPage = $currentPage ?: static::resolveCurrentPage();
5237 return $this->isValidPageNumber($currentPage) ? (int) $currentPage : 1;
5241 $this->hasMore = count($this->items) > $this->perPage;
5242 $this->items = $this->items->slice(0, $this->perPage);
5246 if ($this->hasMore) {
5247 return $this->
url($this->currentPage() + 1);
5252 return $this->hasMore;
5256 if (is_null($presenter) && static::$presenterResolver) {
5257 $presenter = call_user_func(static::$presenterResolver, $this);
5260 return $presenter->render();
5264 return array(
'per_page' => $this->perPage(),
'current_page' => $this->currentPage(),
'next_page_url' => $this->nextPageUrl(),
'prev_page_url' => $this->previousPageUrl(),
'from' => $this->firstItem(),
'to' => $this->lastItem(),
'data' => $this->items->toArray());
5268 return json_encode($this->toArray(), $options);
5274 use RuntimeException;
5280 public static function swap($instance)
5282 static::$resolvedInstance[static::getFacadeAccessor()] = $instance;
5283 static::$app->instance(static::getFacadeAccessor(), $instance);
5287 $name = static::getFacadeAccessor();
5288 if (static::isMock()) {
5289 $mock = static::$resolvedInstance[$name];
5291 $mock = static::createFreshMockInstance($name);
5293 return call_user_func_array(array($mock,
'shouldReceive'), func_get_args());
5297 static::$resolvedInstance[$name] = $mock = static::createMockByName($name);
5305 $class = static::getMockableClass($name);
5306 return $class ? Mockery::mock($class) : Mockery::mock();
5310 $name = static::getFacadeAccessor();
5311 return isset(static::$resolvedInstance[$name]) && static::$resolvedInstance[$name] instanceof MockInterface;
5315 if ($root = static::getFacadeRoot()) {
5316 return get_class($root);
5321 return static::resolveFacadeInstance(static::getFacadeAccessor());
5325 throw new RuntimeException(
'Facade does not implement getFacadeAccessor method.');
5329 if (is_object($name)) {
5332 if (isset(static::$resolvedInstance[$name])) {
5333 return static::$resolvedInstance[$name];
5335 return static::$resolvedInstance[$name] =
static::$app[$name];
5339 unset(static::$resolvedInstance[$name]);
5343 static::$resolvedInstance = array();
5355 $instance = static::getFacadeRoot();
5356 switch (count($args)) {
5358 return $instance->{$method}();
5360 return $instance->{$method}($args[0]);
5362 return $instance->{$method}($args[0], $args[1]);
5364 return $instance->{$method}($args[0], $args[1], $args[2]);
5366 return $instance->{$method}($args[0], $args[1], $args[2], $args[3]);
5368 return call_user_func_array(array($instance, $method), $args);
5375 use BadMethodCallException;
5378 protected static $macros = array();
5379 public static function macro($name, callable $macro)
5381 static::$macros[$name] = $macro;
5383 public static function hasMacro($name)
5385 return isset(static::$macros[$name]);
5387 public static function __callStatic($method, $parameters)
5389 if (static::hasMacro($method)) {
5390 if (static::$macros[$method] instanceof Closure) {
5391 return call_user_func_array(Closure::bind(static::$macros[$method], null, get_called_class()), $parameters);
5393 return call_user_func_array(static::$macros[$method], $parameters);
5396 throw new BadMethodCallException(
"Method {$method} does not exist.");
5400 if (static::hasMacro($method)) {
5401 if (static::$macros[$method] instanceof Closure) {
5402 return call_user_func_array(static::$macros[$method]->bindTo($this, get_class($this)), $parameters);
5404 return call_user_func_array(static::$macros[$method], $parameters);
5407 throw new BadMethodCallException(
"Method {$method} does not exist.");
5416 public static function add($array, $key, $value)
5418 if (is_null(static::get($array, $key))) {
5423 public static function build($array, callable $callback)
5426 foreach ($array as $key => $value) {
5427 list($innerKey, $innerValue) = call_user_func($callback, $key, $value);
5428 $results[$innerKey] = $innerValue;
5434 return array(array_keys($array), array_values($array));
5436 public static function dot($array, $prepend =
'')
5439 foreach ($array as $key => $value) {
5440 if (is_array($value)) {
5441 $results = array_merge($results, static::dot($value, $prepend . $key .
'.'));
5443 $results[$prepend . $key] = $value;
5450 foreach ((array) $keys as $key) {
5451 static::forget($array, $key);
5455 public static function fetch($array, $key)
5457 foreach (explode(
'.', $key) as $segment) {
5459 foreach ($array as $value) {
5460 if (array_key_exists($segment, $value = (array) $value)) {
5461 $results[] = $value[$segment];
5464 $array = array_values($results);
5466 return array_values($results);
5468 public static function first($array, callable $callback, $default = null)
5470 foreach ($array as $key => $value) {
5471 if (call_user_func($callback, $key, $value)) {
5475 return value($default);
5477 public static function last($array, callable $callback, $default = null)
5479 return static::first(array_reverse($array), $callback, $default);
5484 array_walk_recursive($array,
function ($x) use(&$return) {
5489 public static function forget(&$array, $keys)
5491 $original =& $array;
5492 foreach ((array) $keys as $key) {
5493 $parts = explode(
'.', $key);
5494 while (count($parts) > 1) {
5495 $part = array_shift($parts);
5496 if (isset($array[$part]) && is_array($array[$part])) {
5497 $array =& $array[$part];
5500 unset($array[array_shift($parts)]);
5501 $array =& $original;
5504 public static function get($array, $key, $default = null)
5506 if (is_null($key)) {
5509 if (isset($array[$key])) {
5510 return $array[$key];
5512 foreach (explode(
'.', $key) as $segment) {
5513 if (!is_array($array) || !array_key_exists($segment, $array)) {
5514 return value($default);
5516 $array = $array[$segment];
5520 public static function has($array, $key)
5522 if (
empty($array) || is_null($key)) {
5525 if (array_key_exists($key, $array)) {
5528 foreach (explode(
'.', $key) as $segment) {
5529 if (!is_array($array) || !array_key_exists($segment, $array)) {
5532 $array = $array[$segment];
5536 public static function only($array, $keys)
5538 return array_intersect_key($array, array_flip((array) $keys));
5540 public static function pluck($array, $value, $key = null)
5543 foreach ($array as $item) {
5544 $itemValue = data_get($item, $value);
5545 if (is_null($key)) {
5546 $results[] = $itemValue;
5548 $itemKey = data_get($item, $key);
5549 $results[$itemKey] = $itemValue;
5554 public static function pull(&$array, $key, $default = null)
5556 $value = static::get($array, $key, $default);
5557 static::forget($array, $key);
5560 public static function set(&$array, $key, $value)
5562 if (is_null($key)) {
5563 return $array = $value;
5565 $keys = explode(
'.', $key);
5566 while (count($keys) > 1) {
5567 $key = array_shift($keys);
5568 if (!isset($array[$key]) || !is_array($array[$key])) {
5569 $array[$key] = array();
5571 $array =& $array[$key];
5573 $array[array_shift($keys)] = $value;
5576 public static function sort($array, callable $callback)
5578 return Collection::make($array)->sortBy($callback)->all();
5580 public static function where($array, callable $callback)
5582 $filtered = array();
5583 foreach ($array as $key => $value) {
5584 if (call_user_func($callback, $key, $value)) {
5585 $filtered[$key] = $value;
5593 use RuntimeException;
5599 protected static $snakeCache = array();
5600 protected static $camelCache = array();
5601 protected static $studlyCache = array();
5604 return StaticStringy::toAscii($value);
5608 if (isset(static::$camelCache[$value])) {
5609 return static::$camelCache[$value];
5611 return static::$camelCache[$value] = lcfirst(static::studly($value));
5615 foreach ((array) $needles as $needle) {
5616 if ($needle !=
'' && strpos($haystack, $needle) !==
false) {
5624 foreach ((array) $needles as $needle) {
5625 if ((
string) $needle === substr($haystack, -strlen($needle))) {
5633 $quoted = preg_quote($cap,
'/');
5634 return preg_replace(
'/(?:' . $quoted .
')+$/',
'', $value) . $cap;
5636 public static function is($pattern, $value)
5638 if ($pattern == $value) {
5641 $pattern = preg_quote($pattern,
'#');
5642 $pattern = str_replace(
'\\*',
'.*', $pattern) .
'\\z';
5643 return (
bool) preg_match(
'#^' . $pattern .
'#', $value);
5647 return mb_strlen($value);
5649 public static function limit($value, $limit = 100, $end =
'...')
5651 if (mb_strlen($value) <= $limit) {
5654 return rtrim(mb_substr($value, 0, $limit,
'UTF-8')) . $end;
5658 return mb_strtolower($value);
5660 public static function words($value, $words = 100, $end =
'...')
5662 preg_match(
'/^\\s*+(?:\\S++\\s*+){1,' . $words .
'}/u', $value, $matches);
5663 if (!isset($matches[0]) || strlen($value) === strlen($matches[0])) {
5666 return rtrim($matches[0]) . $end;
5670 return static::contains($callback,
'@') ? explode(
'@', $callback, 2) : array($callback, $default);
5674 return Pluralizer::plural($value,
$count);
5678 if (!function_exists(
'openssl_random_pseudo_bytes')) {
5679 throw new RuntimeException(
'OpenSSL extension is required.');
5681 $bytes = openssl_random_pseudo_bytes($length * 2);
5682 if ($bytes ===
false) {
5683 throw new RuntimeException(
'Unable to generate random string.');
5685 return substr(str_replace(array(
'/',
'+',
'='),
'', base64_encode($bytes)), 0, $length);
5689 $pool =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
5690 return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
5694 return mb_strtoupper($value);
5698 return mb_convert_case($value, MB_CASE_TITLE,
'UTF-8');
5702 return Pluralizer::singular($value);
5704 public static function slug($title, $separator =
'-')
5706 $title = static::ascii($title);
5707 $flip = $separator ==
'-' ?
'_' :
'-';
5708 $title = preg_replace(
'![' . preg_quote($flip) .
']+!u', $separator, $title);
5709 $title = preg_replace(
'![^' . preg_quote($separator) .
'\\pL\\pN\\s]+!u',
'', mb_strtolower($title));
5710 $title = preg_replace(
'![' . preg_quote($separator) .
'\\s]+!u', $separator, $title);
5711 return trim($title, $separator);
5713 public static function snake($value, $delimiter =
'_')
5715 $key = $value . $delimiter;
5716 if (isset(static::$snakeCache[$key])) {
5717 return static::$snakeCache[$key];
5719 if (!ctype_lower($value)) {
5720 $value = strtolower(preg_replace(
'/(.)(?=[A-Z])/',
'$1' . $delimiter, $value));
5722 return static::$snakeCache[$key] = $value;
5726 foreach ((array) $needles as $needle) {
5727 if ($needle !=
'' && strpos($haystack, $needle) === 0) {
5736 if (isset(static::$studlyCache[$key])) {
5737 return static::$studlyCache[$key];
5739 $value = ucwords(str_replace(array(
'-',
'_'),
' ', $value));
5740 return static::$studlyCache[$key] = str_replace(
' ',
'', $value);
5756 const TYPE_DEPRECATION = -100;
5757 private $levels = array(E_DEPRECATED =>
'Deprecated', E_USER_DEPRECATED =>
'User Deprecated', E_NOTICE =>
'Notice', E_USER_NOTICE =>
'User Notice', E_STRICT =>
'Runtime Notice', E_WARNING =>
'Warning', E_USER_WARNING =>
'User Warning', E_COMPILE_WARNING =>
'Compile Warning', E_CORE_WARNING =>
'Core Warning', E_USER_ERROR =>
'User Error', E_RECOVERABLE_ERROR =>
'Catchable Fatal Error', E_COMPILE_ERROR =>
'Compile Error', E_PARSE =>
'Parse Error', E_ERROR =>
'Error', E_CORE_ERROR =>
'Core Error');
5758 private $loggers = array(E_DEPRECATED => array(null, LogLevel::INFO), E_USER_DEPRECATED => array(null, LogLevel::INFO), E_NOTICE => array(null, LogLevel::NOTICE), E_USER_NOTICE => array(null, LogLevel::NOTICE), E_STRICT => array(null, LogLevel::NOTICE), E_WARNING => array(null, LogLevel::WARNING), E_USER_WARNING => array(null, LogLevel::WARNING), E_COMPILE_WARNING => array(null, LogLevel::WARNING), E_CORE_WARNING => array(null, LogLevel::WARNING), E_USER_ERROR => array(null, LogLevel::ERROR), E_RECOVERABLE_ERROR => array(null, LogLevel::ERROR), E_COMPILE_ERROR => array(null, LogLevel::EMERGENCY), E_PARSE => array(null, LogLevel::EMERGENCY), E_ERROR => array(null, LogLevel::EMERGENCY), E_CORE_ERROR => array(null, LogLevel::EMERGENCY));
5759 private $thrownErrors = 8191;
5760 private $scopedErrors = 8191;
5761 private $tracedErrors = 30715;
5762 private $screamedErrors = 85;
5763 private $loggedErrors = 0;
5764 private $loggedTraces = array();
5765 private $isRecursive = 0;
5766 private $exceptionHandler;
5767 private static $reservedMemory;
5768 private static $stackedErrors = array();
5769 private static $stackedErrorLevels = array();
5770 private $displayErrors = 8191;
5771 public static function register($handler = null, $replace =
true)
5773 if (null === self::$reservedMemory) {
5774 self::$reservedMemory = str_repeat(
'x', 10240);
5775 register_shutdown_function(__CLASS__ .
'::handleFatalError');
5778 if ($handlerIsNew = !$handler instanceof
self) {
5779 if (null !== $handler) {
5780 $levels = $replace ? $handler : 0;
5783 $handler =
new static();
5785 $prev = set_error_handler(array($handler,
'handleError'), $handler->thrownErrors | $handler->loggedErrors);
5786 if ($handlerIsNew && is_array($prev) && $prev[0] instanceof
self) {
5787 $handler = $prev[0];
5790 if ($replace || !$prev) {
5791 $handler->setExceptionHandler(set_exception_handler(array($handler,
'handleException')));
5793 restore_error_handler();
5795 $handler->throwAt($levels & $handler->thrownErrors,
true);
5801 if (is_array($levels)) {
5802 foreach ($levels as $type => $logLevel) {
5803 if (
empty($this->loggers[$type][0]) || $replace) {
5804 $loggers[$type] = array($logger, $logLevel);
5808 if (null === $levels) {
5809 $levels = E_ALL | E_STRICT;
5811 foreach ($this->loggers as $type => $log) {
5812 if ($type & $levels && (
empty($log[0]) || $replace)) {
5814 $loggers[$type] = $log;
5818 $this->setLoggers($loggers);
5822 $prevLogged = $this->loggedErrors;
5823 $prev = $this->loggers;
5824 foreach ($loggers as $type => $log) {
5825 if (!isset($prev[$type])) {
5826 throw new \InvalidArgumentException(
'Unknown error type: ' . $type);
5828 if (!is_array($log)) {
5830 } elseif (!array_key_exists(0, $log)) {
5831 throw new \InvalidArgumentException(
'No logger provided');
5833 if (null === $log[0]) {
5834 $this->loggedErrors &= ~$type;
5836 $this->loggedErrors |= $type;
5838 throw new \InvalidArgumentException(
'Invalid logger provided');
5840 $this->loggers[$type] = $log + $prev[$type];
5842 $this->reRegister($prevLogged | $this->thrownErrors);
5847 if (null !== $handler && !is_callable($handler)) {
5848 throw new \LogicException(
'The exception handler must be a valid PHP callable.');
5850 $prev = $this->exceptionHandler;
5851 $this->exceptionHandler = $handler;
5854 public function throwAt($levels, $replace =
false)
5856 $prev = $this->thrownErrors;
5857 $this->thrownErrors = ($levels | E_RECOVERABLE_ERROR | E_USER_ERROR) & ~E_USER_DEPRECATED & ~E_DEPRECATED;
5859 $this->thrownErrors |= $prev;
5861 $this->reRegister($prev | $this->loggedErrors);
5862 $this->displayErrors = $this->thrownErrors;
5865 public function scopeAt($levels, $replace =
false)
5867 $prev = $this->scopedErrors;
5868 $this->scopedErrors = (int) $levels;
5870 $this->scopedErrors |= $prev;
5874 public function traceAt($levels, $replace =
false)
5876 $prev = $this->tracedErrors;
5877 $this->tracedErrors = (int) $levels;
5879 $this->tracedErrors |= $prev;
5885 $prev = $this->screamedErrors;
5886 $this->screamedErrors = (int) $levels;
5888 $this->screamedErrors |= $prev;
5892 private function reRegister($prev)
5894 if ($prev !== $this->thrownErrors | $this->loggedErrors) {
5895 $handler = set_error_handler(
'var_dump', 0);
5896 $handler = is_array($handler) ? $handler[0] : null;
5897 restore_error_handler();
5898 if ($handler === $this) {
5899 restore_error_handler();
5900 set_error_handler(array($this,
'handleError'), $this->thrownErrors | $this->loggedErrors);
5904 public function handleError($type, $message, $file, $line, array $context)
5906 $level = error_reporting() | E_RECOVERABLE_ERROR | E_USER_ERROR;
5907 $log = $this->loggedErrors & $type;
5908 $throw = $this->thrownErrors & $type & $level;
5909 $type &= $level | $this->screamedErrors;
5910 if ($type && ($log || $throw)) {
5911 if (PHP_VERSION_ID < 50400 && isset($context[
'GLOBALS']) && $this->scopedErrors & $type) {
5913 unset($e[
'GLOBALS'], $context);
5917 if ($this->scopedErrors & $type && class_exists(
'Symfony\\Component\\Debug\\Exception\\ContextErrorException')) {
5918 $throw =
new ContextErrorException($this->levels[$type] .
': ' . $message, 0, $type, $file, $line, $context);
5920 $throw = new \ErrorException($this->levels[$type] .
': ' . $message, 0, $type, $file, $line);
5922 if (PHP_VERSION_ID <= 50407 && (PHP_VERSION_ID >= 50400 || PHP_VERSION_ID <= 50317)) {
5927 $e = md5(
"{$type}/{$line}/{$file} {$message}",
true);
5929 if (!($this->tracedErrors & $type) || isset($this->loggedTraces[$e])) {
5932 $this->loggedTraces[$e] = 1;
5934 $e = compact(
'type',
'file',
'line',
'level');
5935 if ($type & $level) {
5936 if ($this->scopedErrors & $type) {
5937 $e[
'context'] = $context;
5939 $e[
'stack'] = debug_backtrace(
true);
5942 $e[
'stack'] = debug_backtrace(PHP_VERSION_ID >= 50306 ? DEBUG_BACKTRACE_IGNORE_ARGS :
false);
5945 if ($this->isRecursive) {
5947 } elseif (self::$stackedErrorLevels) {
5948 self::$stackedErrors[] = array($this->loggers[$type], $message, $e);
5951 $this->isRecursive =
true;
5952 $this->loggers[$type][0]->log($this->loggers[$type][1], $message, $e);
5953 $this->isRecursive =
false;
5954 }
catch (\Exception $e) {
5955 $this->isRecursive =
false;
5960 return $type && $log;
5964 $level = error_reporting();
5965 if ($this->loggedErrors & E_ERROR & ($level | $this->screamedErrors)) {
5966 $e = array(
'type' => E_ERROR,
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'level' => $level,
'stack' => $exception->getTrace());
5968 $message =
'Fatal ' . $exception->getMessage();
5969 } elseif ($exception instanceof \ErrorException) {
5970 $message =
'Uncaught ' . $exception->getMessage();
5972 $e[
'context'] = $exception->getContext();
5975 $message =
'Uncaught Exception: ' . $exception->getMessage();
5977 if ($this->loggedErrors & $e[
'type']) {
5978 $this->loggers[$e[
'type']][0]->log($this->loggers[$e[
'type']][1], $message, $e);
5982 foreach ($this->getFatalErrorHandlers() as $handler) {
5983 if ($e = $handler->handleError($error, $exception)) {
5989 if (
empty($this->exceptionHandler)) {
5993 call_user_func($this->exceptionHandler, $exception);
5994 }
catch (\Exception $handlerException) {
5995 $this->exceptionHandler = null;
5996 $this->handleException($handlerException);
6001 self::$reservedMemory =
'';
6002 $handler = set_error_handler(
'var_dump', 0);
6003 $handler = is_array($handler) ? $handler[0] : null;
6004 restore_error_handler();
6005 if ($handler instanceof
self) {
6006 if (null === $error) {
6007 $error = error_get_last();
6010 while (self::$stackedErrorLevels) {
6011 static::unstackErrors();
6013 }
catch (\Exception $exception) {
6015 if ($error && $error[
'type'] & (E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR)) {
6016 $handler->throwAt(0,
true);
6017 if (0 === strpos($error[
'message'],
'Allowed memory') || 0 === strpos($error[
'message'],
'Out of memory')) {
6018 $exception =
new OutOfMemoryException($handler->levels[$error[
'type']] .
': ' . $error[
'message'], 0, $error[
'type'], $error[
'file'], $error[
'line'], 2,
false);
6020 $exception =
new FatalErrorException($handler->levels[$error[
'type']] .
': ' . $error[
'message'], 0, $error[
'type'], $error[
'file'], $error[
'line'], 2,
true);
6022 } elseif (!isset($exception)) {
6026 $handler->handleException($exception, $error);
6033 self::$stackedErrorLevels[] = error_reporting(error_reporting() | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR);
6037 $level = array_pop(self::$stackedErrorLevels);
6038 if (null !== $level) {
6039 $e = error_reporting($level);
6040 if ($e !== ($level | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR)) {
6041 error_reporting($e);
6044 if (
empty(self::$stackedErrorLevels)) {
6045 $errors = self::$stackedErrors;
6046 self::$stackedErrors = array();
6047 foreach ($errors as $e) {
6048 $e[0][0]->log($e[0][1], $e[1], $e[2]);
6058 $level = null === $level ? error_reporting() : $level;
6059 $this->throwAt($level,
true);
6063 if ($displayErrors) {
6064 $this->throwAt($this->displayErrors,
true);
6066 $displayErrors = $this->displayErrors;
6067 $this->throwAt(0,
true);
6068 $this->displayErrors = $displayErrors;
6073 $handler = set_error_handler(
'var_dump', 0);
6074 $handler = is_array($handler) ? $handler[0] : null;
6075 restore_error_handler();
6076 if (!$handler instanceof
self) {
6079 if (
'deprecation' === $channel) {
6080 $handler->setDefaultLogger($logger, E_DEPRECATED | E_USER_DEPRECATED,
true);
6081 $handler->screamAt(E_DEPRECATED | E_USER_DEPRECATED);
6082 } elseif (
'scream' === $channel) {
6083 $handler->setDefaultLogger($logger, E_ALL | E_STRICT,
false);
6084 $handler->screamAt(E_ALL | E_STRICT);
6085 } elseif (
'emergency' === $channel) {
6086 $handler->setDefaultLogger($logger, E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR,
true);
6087 $handler->screamAt(E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR);
6090 public function handle($level, $message, $file =
'unknown', $line = 0, $context = array())
6092 return $this->handleError($level, $message, $file, $line, (array) $context);
6096 static::handleFatalError();
6101 private static $displayErrors = null;
6104 if (null === self::$displayErrors) {
6105 self::$displayErrors = ini_set(
'display_errors', 1);
6110 if (null !== self::$displayErrors) {
6111 ini_set(
'display_errors', self::$displayErrors);
6112 self::$displayErrors = null;
6128 protected $items = array();
6131 $this->items = $items;
6135 return array_has($this->items, $key);
6137 public function get($key, $default = null)
6139 return array_get($this->items, $key, $default);
6141 public function set($key, $value = null)
6143 if (is_array($key)) {
6144 foreach ($key as $innerKey => $innerValue) {
6145 array_set($this->items, $innerKey, $innerValue);
6148 array_set($this->items, $key, $value);
6153 $array = $this->
get($key);
6154 array_unshift($array, $value);
6155 $this->
set($key, $array);
6159 $array = $this->
get($key);
6161 $this->
set($key, $array);
6165 return $this->items;
6169 return $this->has($key);
6173 return $this->
get($key);
6177 $this->
set($key, $value);
6181 $this->
set($key, null);
6188 protected $parsed = array();
6191 if (isset($this->parsed[$key])) {
6192 return $this->parsed[$key];
6194 if (strpos($key,
'::') ===
false) {
6195 $segments = explode(
'.', $key);
6196 $parsed = $this->parseBasicSegments($segments);
6198 $parsed = $this->parseNamespacedSegments($key);
6200 return $this->parsed[$key] = $parsed;
6204 $group = $segments[0];
6205 if (count($segments) == 1) {
6206 return array(null, $group, null);
6208 $item = implode(
'.', array_slice($segments, 1));
6209 return array(null, $group, $item);
6214 list($namespace, $item) = explode(
'::', $key);
6215 $itemSegments = explode(
'.', $item);
6216 $groupAndItem = array_slice($this->parseBasicSegments($itemSegments), 1);
6217 return array_merge(array($namespace), $groupAndItem);
6221 $this->parsed[$key] = $parsed;
6235 return file_exists(
$path);
6239 if ($this->isFile(
$path)) {
6240 return file_get_contents(
$path);
6246 if ($this->isFile(
$path)) {
6247 return require
$path;
6257 return file_put_contents(
$path, $contents,
$lock ? LOCK_EX : 0);
6261 if ($this->exists(
$path)) {
6262 return $this->put(
$path, $data . $this->
get(
$path));
6264 return $this->put(
$path, $data);
6268 return file_put_contents(
$path, $data, FILE_APPEND);
6270 public function delete($paths)
6272 $paths = is_array($paths) ? $paths : func_get_args();
6274 foreach ($paths as
$path) {
6275 if (!@unlink($path)) {
6283 return rename(
$path, $target);
6287 return copy(
$path, $target);
6291 return pathinfo(
$path, PATHINFO_FILENAME);
6295 return pathinfo(
$path, PATHINFO_EXTENSION);
6299 return filetype(
$path);
6303 return finfo_file(finfo_open(FILEINFO_MIME_TYPE),
$path);
6307 return filesize(
$path);
6311 return filemtime(
$path);
6315 return is_dir($directory);
6319 return is_writable(
$path);
6323 return is_file($file);
6325 public function glob($pattern, $flags = 0)
6327 return glob($pattern, $flags);
6331 $glob = glob($directory .
'/*');
6332 if ($glob ===
false) {
6335 return array_filter($glob,
function ($file) {
6336 return filetype($file) ==
'file';
6341 return iterator_to_array(Finder::create()->files()->in($directory),
false);
6345 $directories = array();
6346 foreach (Finder::create()->in($directory)->directories()->depth(0) as $dir) {
6347 $directories[] = $dir->getPathname();
6349 return $directories;
6354 return @mkdir(
$path, $mode, $recursive);
6356 return mkdir(
$path, $mode, $recursive);
6360 if (!$this->isDirectory($directory)) {
6363 $options = $options ?: FilesystemIterator::SKIP_DOTS;
6364 if (!$this->isDirectory($destination)) {
6365 $this->makeDirectory($destination, 511,
true);
6367 $items =
new FilesystemIterator($directory, $options);
6368 foreach ($items as $item) {
6369 $target = $destination .
'/' . $item->getBasename();
6370 if ($item->isDir()) {
6371 $path = $item->getPathname();
6372 if (!$this->copyDirectory(
$path, $target, $options)) {
6376 if (!$this->copy($item->getPathname(), $target)) {
6385 if (!$this->isDirectory($directory)) {
6388 $items =
new FilesystemIterator($directory);
6389 foreach ($items as $item) {
6390 if ($item->isDir() && !$item->isLink()) {
6391 $this->deleteDirectory($item->getPathname());
6393 $this->
delete($item->getPathname());
6403 return $this->deleteDirectory($directory,
true);
6411 protected $registered =
false;
6413 private function __construct($aliases)
6415 $this->aliases = $aliases;
6419 if (is_null(static::$instance)) {
6420 return static::$instance =
new static($aliases);
6422 $aliases = array_merge(static::$instance->getAliases(), $aliases);
6423 static::$instance->setAliases($aliases);
6424 return static::$instance;
6428 if (isset($this->aliases[$alias])) {
6429 return class_alias($this->aliases[$alias], $alias);
6434 $this->aliases[$class] = $alias;
6436 public function register()
6438 if (!$this->registered) {
6439 $this->prependToLoaderStack();
6440 $this->registered =
true;
6445 spl_autoload_register(array($this,
'load'),
true,
true);
6449 return $this->aliases;
6453 $this->aliases = $aliases;
6457 return $this->registered;
6461 $this->registered = $value;
6467 private function __clone()
6483 $this->files = $files;
6484 $this->manifestPath = $manifestPath;
6486 public function load(array $providers)
6488 $manifest = $this->loadManifest();
6489 if ($this->shouldRecompile($manifest, $providers)) {
6490 $manifest = $this->compileManifest($providers);
6492 foreach ($manifest[
'when'] as $provider => $events) {
6493 $this->registerLoadEvents($provider, $events);
6495 foreach ($manifest[
'eager'] as $provider) {
6496 $this->app->register($this->createProvider($provider));
6498 $this->app->setDeferredServices($manifest[
'deferred']);
6502 if (count($events) < 1) {
6506 $app->make(
'events')->listen($events,
function () use(
$app, $provider) {
6507 $app->register($provider);
6512 $manifest = $this->freshManifest($providers);
6513 foreach ($providers as $provider) {
6514 $instance = $this->createProvider($provider);
6515 if ($instance->isDeferred()) {
6516 foreach ($instance->provides() as $service) {
6517 $manifest[
'deferred'][$service] = $provider;
6519 $manifest[
'when'][$provider] = $instance->when();
6521 $manifest[
'eager'][] = $provider;
6524 return $this->writeManifest($manifest);
6528 return new $provider($this->app);
6532 return is_null($manifest) || $manifest[
'providers'] != $providers;
6536 if ($this->files->exists($this->manifestPath)) {
6537 $manifest = json_decode($this->files->get($this->manifestPath),
true);
6538 return array_merge(array(
'when' => array()), $manifest);
6543 $this->files->put($this->manifestPath, json_encode($manifest, JSON_PRETTY_PRINT));
6548 return array(
'providers' => $providers,
'eager' => array(),
'deferred' => array());
6556 public function register()
6558 $this->app->singleton(
'cookie',
function (
$app) {
6559 $config =
$app[
'config'][
'session'];
6560 return (
new CookieJar())->setDefaultPathAndDomain($config[
'path'], $config[
'domain']);
6573 Model::setConnectionResolver($this->app[
'db']);
6574 Model::setEventDispatcher($this->app[
'events']);
6576 public function register()
6578 $this->registerQueueableEntityResolver();
6579 $this->app->singleton(
'db.factory',
function (
$app) {
6582 $this->app->singleton(
'db',
function (
$app) {
6588 $this->app->singleton(
'Illuminate\\Contracts\\Queue\\EntityResolver',
function () {
6589 return new Eloquent\QueueEntityResolver();
6598 public function register()
6600 $this->app->singleton(
'encrypter',
function (
$app) {
6602 if (
$app[
'config']->has(
'app.cipher')) {
6603 $encrypter->setCipher(
$app[
'config'][
'app.cipher']);
6614 public function register()
6616 $this->registerNativeFilesystem();
6617 $this->registerFlysystem();
6621 $this->app->singleton(
'files',
function () {
6627 $this->registerManager();
6628 $this->app->singleton(
'filesystem.disk',
function () {
6629 return $this->app[
'filesystem']->disk($this->getDefaultDriver());
6631 $this->app->singleton(
'filesystem.cloud',
function () {
6632 return $this->app[
'filesystem']->disk($this->getCloudDriver());
6637 $this->app->singleton(
'filesystem',
function () {
6643 return $this->app[
'config'][
'filesystems.default'];
6647 return $this->app[
'config'][
'filesystems.cloud'];
6655 public function register()
6657 $this->registerSessionManager();
6658 $this->registerSessionDriver();
6659 $this->app->singleton(
'Illuminate\\Session\\Middleware\\StartSession');
6663 $this->app->singleton(
'session',
function (
$app) {
6669 $this->app->singleton(
'session.store',
function (
$app) {
6670 $manager =
$app[
'session'];
6671 return $manager->driver();
6684 public function register()
6686 $this->registerEngineResolver();
6687 $this->registerViewFinder();
6688 $this->registerFactory();
6692 $this->app->singleton(
'view.engine.resolver',
function () {
6694 foreach (array(
'php',
'blade') as $engine) {
6695 $this->{
'register' . ucfirst($engine) .
'Engine'}($resolver);
6702 $resolver->register(
'php',
function () {
6709 $app->singleton(
'blade.compiler',
function (
$app) {
6710 $cache =
$app[
'config'][
'view.compiled'];
6713 $resolver->register(
'blade',
function () use(
$app) {
6719 $this->app->bind(
'view.finder',
function (
$app) {
6720 $paths =
$app[
'config'][
'view.paths'];
6726 $this->app->singleton(
'view',
function (
$app) {
6727 $resolver =
$app[
'view.engine.resolver'];
6728 $finder =
$app[
'view.finder'];
6729 $env =
new Factory($resolver, $finder,
$app[
'events']);
6730 $env->setContainer(
$app);
6731 $env->share(
'app',
$app);
6742 protected function callWithDependencies($instance, $method)
6744 return call_user_func_array(array($instance, $method), $this->resolveClassMethodDependencies(array(), $instance, $method));
6746 protected function resolveClassMethodDependencies(array $parameters, $instance, $method)
6748 if (!method_exists($instance, $method)) {
6751 return $this->resolveMethodDependencies($parameters,
new ReflectionMethod($instance, $method));
6753 public function resolveMethodDependencies(array $parameters, ReflectionFunctionAbstract $reflector)
6755 foreach ($reflector->getParameters() as $key => $parameter) {
6756 $class = $parameter->getClass();
6757 if ($class && !$this->alreadyInParameters($class->name, $parameters)) {
6758 array_splice($parameters, $key, 0, array($this->container->make($class->name)));
6763 protected function alreadyInParameters($class, array $parameters)
6765 return !is_null(array_first($parameters,
function ($key, $value) use($class) {
6766 return $value instanceof $class;
6791 protected $middleware = array();
6792 protected $patternFilters = array();
6793 protected $regexFilters = array();
6794 protected $binders = array();
6795 protected $patterns = array();
6796 protected $groupStack = array();
6797 public static $verbs = array(
'GET',
'HEAD',
'POST',
'PUT',
'PATCH',
'DELETE',
'OPTIONS');
6800 $this->events = $events;
6806 return $this->addRoute(array(
'GET',
'HEAD'),
$uri, $action);
6810 return $this->addRoute(
'POST',
$uri, $action);
6814 return $this->addRoute(
'PUT',
$uri, $action);
6818 return $this->addRoute(
'PATCH',
$uri, $action);
6820 public function delete(
$uri, $action)
6822 return $this->addRoute(
'DELETE',
$uri, $action);
6826 return $this->addRoute(
'OPTIONS',
$uri, $action);
6830 $verbs = array(
'GET',
'HEAD',
'POST',
'PUT',
'PATCH',
'DELETE');
6831 return $this->addRoute($verbs,
$uri, $action);
6835 return $this->addRoute(array_map(
'strtoupper', (array) $methods),
$uri, $action);
6839 foreach ($controllers as
$uri => $name) {
6840 $this->controller(
$uri, $name);
6845 $prepended = $controller;
6846 if (!
empty($this->groupStack)) {
6847 $prepended = $this->prependGroupUses($controller);
6850 foreach ($routable as $method => $routes) {
6851 foreach ($routes as $route) {
6852 $this->registerInspected($route, $controller, $method, $names);
6855 $this->addFallthroughRoute($controller,
$uri);
6859 $action = array(
'uses' => $controller .
'@' . $method);
6860 $action[
'as'] = array_get($names, $method);
6861 $this->{$route[
'verb']}($route[
'uri'], $action);
6865 $missing = $this->
any(
$uri .
'/{_missing}', $controller .
'@missingMethod');
6866 $missing->where(
'_missing',
'(.*)');
6870 foreach ($resources as $name => $controller) {
6871 $this->resource($name, $controller);
6874 public function resource($name, $controller, array $options = array())
6878 public function group(array $attributes, Closure $callback)
6880 $this->updateGroupStack($attributes);
6881 call_user_func($callback, $this);
6882 array_pop($this->groupStack);
6886 if (!
empty($this->groupStack)) {
6887 $attributes = $this->mergeGroup($attributes, last($this->groupStack));
6889 $this->groupStack[] = $attributes;
6893 return $this->mergeGroup($new, last($this->groupStack));
6897 $new[
'namespace'] = static::formatUsesPrefix($new, $old);
6898 $new[
'prefix'] = static::formatGroupPrefix($new, $old);
6899 if (isset($new[
'domain'])) {
6900 unset($old[
'domain']);
6902 $new[
'where'] = array_merge(array_get($old,
'where', array()), array_get($new,
'where', array()));
6903 return array_merge_recursive(array_except($old, array(
'namespace',
'prefix',
'where')), $new);
6907 if (isset($new[
'namespace']) && isset($old[
'namespace'])) {
6908 return trim(array_get($old,
'namespace'),
'\\') .
'\\' . trim($new[
'namespace'],
'\\');
6909 } elseif (isset($new[
'namespace'])) {
6910 return trim($new[
'namespace'],
'\\');
6912 return array_get($old,
'namespace');
6916 if (isset($new[
'prefix'])) {
6917 return trim(array_get($old,
'prefix'),
'/') .
'/' . trim($new[
'prefix'],
'/');
6919 return array_get($old,
'prefix');
6923 if (!
empty($this->groupStack)) {
6924 $last = end($this->groupStack);
6925 return isset($last[
'prefix']) ? $last[
'prefix'] :
'';
6931 return $this->routes->add($this->createRoute($methods,
$uri, $action));
6935 if ($this->actionReferencesController($action)) {
6936 $action = $this->convertToControllerAction($action);
6938 $route = $this->newRoute($methods, $this->prefix(
$uri), $action);
6939 if ($this->hasGroupStack()) {
6940 $this->mergeGroupAttributesIntoRoute($route);
6942 $this->addWhereClausesToRoute($route);
6947 return (
new Route($methods,
$uri, $action))->setContainer($this->container);
6951 return trim(trim($this->getLastGroupPrefix(),
'/') .
'/' . trim(
$uri,
'/'),
'/') ?:
'/';
6955 $route->where(array_merge($this->patterns, array_get($route->getAction(),
'where', array())));
6960 $action = $this->mergeWithLastGroup($route->getAction());
6961 $route->setAction($action);
6965 if ($action instanceof Closure) {
6968 return is_string($action) || is_string(array_get($action,
'uses'));
6972 if (is_string($action)) {
6973 $action = array(
'uses' => $action);
6975 if (!
empty($this->groupStack)) {
6976 $action[
'uses'] = $this->prependGroupUses($action[
'uses']);
6978 $action[
'controller'] = $action[
'uses'];
6983 $group = last($this->groupStack);
6984 return isset($group[
'namespace']) && strpos($uses,
'\\') !== 0 ? $group[
'namespace'] .
'\\' . $uses : $uses;
6988 $this->currentRequest = $request;
6989 $response = $this->callFilter(
'before', $request);
6991 $response = $this->dispatchToRoute($request);
6994 $this->callFilter(
'after', $request,
$response);
6999 $route = $this->findRoute($request);
7003 $this->events->fire(
'router.matched', array($route, $request));
7004 $response = $this->callRouteBefore($route, $request);
7006 $response = $this->runRouteWithinStack($route, $request);
7009 $this->callRouteAfter($route, $request,
$response);
7014 $middleware = $this->gatherRouteMiddlewares($route);
7015 return (
new Pipeline($this->container))->send($request)->through($middleware)->then(
function ($request) use($route) {
7016 return $this->prepareResponse($request, $route->
run($request));
7021 return Collection::make($route->
middleware())->
map(
function ($m) {
7022 return Collection::make(array_get($this->middleware, $m, $m));
7023 })->collapse()->all();
7027 $this->current = $route = $this->routes->match($request);
7028 $this->container->instance(
'Illuminate\\Routing\\Route', $route);
7029 return $this->substituteBindings($route);
7033 foreach ($route->parameters() as $key => $value) {
7034 if (isset($this->binders[$key])) {
7035 $route->setParameter($key, $this->performBinding($key, $value, $route));
7042 return call_user_func($this->binders[$key], $value, $route);
7046 $this->events->listen(
'router.matched', $callback);
7050 $this->addGlobalFilter(
'before', $callback);
7054 $this->addGlobalFilter(
'after', $callback);
7058 $this->events->listen(
'router.' .
$filter, $this->parseFilter($callback));
7062 return $this->middleware;
7066 $this->middleware[$name] = $class;
7071 $this->events->listen(
'router.filter: ' . $name, $this->parseFilter($callback));
7075 if (is_string($callback) && !str_contains($callback,
'@')) {
7076 return $callback .
'@filter';
7080 public function when($pattern, $name, $methods = null)
7082 if (!is_null($methods)) {
7083 $methods = array_map(
'strtoupper', (array) $methods);
7085 $this->patternFilters[$pattern][] = compact(
'name',
'methods');
7089 if (!is_null($methods)) {
7090 $methods = array_map(
'strtoupper', (array) $methods);
7092 $this->regexFilters[$pattern][] = compact(
'name',
'methods');
7094 public function model($key, $class, Closure $callback = null)
7096 $this->bind($key,
function ($value) use($class, $callback) {
7097 if (is_null($value)) {
7100 if ($model = (
new $class())->find($value)) {
7103 if ($callback instanceof Closure) {
7104 return call_user_func($callback, $value);
7109 public function bind($key, $binder)
7111 if (is_string($binder)) {
7112 $binder = $this->createClassBinding($binder);
7114 $this->binders[str_replace(
'-',
'_', $key)] = $binder;
7118 return function ($value, $route) use($binding) {
7119 $segments = explode(
'@', $binding);
7120 $method = count($segments) == 2 ? $segments[1] :
'bind';
7121 $callable = array($this->container->make($segments[0]), $method);
7122 return call_user_func($callable, $value, $route);
7127 $this->patterns[$key] = $pattern;
7131 foreach ($patterns as $key => $pattern) {
7132 $this->pattern($key, $pattern);
7137 return $this->events->until(
'router.' .
$filter, array($request,
$response));
7141 $response = $this->callPatternFilters($route, $request);
7142 return $response ?: $this->callAttachedBefores($route, $request);
7146 foreach ($this->findPatternFilters($request) as
$filter => $parameters) {
7147 $response = $this->callRouteFilter(
$filter, $parameters, $route, $request);
7156 list(
$path, $method) = array($request->path(), $request->getMethod());
7157 foreach ($this->patternFilters as $pattern => $filters) {
7158 if (str_is($pattern,
$path)) {
7159 $merge = $this->patternsByMethod($method, $filters);
7160 $results = array_merge($results, $merge);
7163 foreach ($this->regexFilters as $pattern => $filters) {
7164 if (preg_match($pattern,
$path)) {
7165 $merge = $this->patternsByMethod($method, $filters);
7166 $results = array_merge($results, $merge);
7174 foreach ($filters as
$filter) {
7175 if ($this->filterSupportsMethod($filter, $method)) {
7176 $parsed = Route::parseFilters($filter[
'name']);
7177 $results = array_merge($results, $parsed);
7184 $methods =
$filter[
'methods'];
7185 return is_null($methods) || in_array($method, $methods);
7189 foreach ($route->beforeFilters() as
$filter => $parameters) {
7190 $response = $this->callRouteFilter($filter, $parameters, $route, $request);
7198 foreach ($route->afterFilters() as
$filter => $parameters) {
7199 $this->callRouteFilter($filter, $parameters, $route, $request,
$response);
7204 $data = array_merge(array($route, $request,
$response), $parameters);
7205 return $this->events->until(
'router.filter: ' .
$filter, $this->cleanFilterParameters($data));
7209 return array_filter($parameters,
function ($p) {
7210 return !is_null($p) && $p !==
'';
7215 if (!
$response instanceof SymfonyResponse) {
7222 return !
empty($this->groupStack);
7226 return $this->groupStack;
7228 public function input($key, $default = null)
7230 return $this->current()->parameter($key, $default);
7234 return $this->current();
7238 return $this->current;
7242 return $this->routes->hasNamedRoute($name);
7246 return $this->current() ? $this->current()->getName() : null;
7250 foreach (func_get_args() as $pattern) {
7251 if (str_is($pattern, $this->currentRouteName())) {
7259 return $this->current() ? $this->current()->getName() == $name :
false;
7263 if (!$this->current()) {
7266 $action = $this->current()->getAction();
7267 return isset($action[
'controller']) ? $action[
'controller'] : null;
7271 foreach (func_get_args() as $pattern) {
7272 if (str_is($pattern, $this->currentRouteAction())) {
7280 return $this->currentRouteAction() == $action;
7284 return $this->currentRequest;
7288 return $this->routes;
7292 foreach ($routes as $route) {
7293 $route->setContainer($this->container);
7295 $this->routes = $routes;
7296 $this->container->instance(
'routes', $this->routes);
7300 return $this->patterns;
7323 protected $defaults = array();
7324 protected $wheres = array();
7333 $this->methods = (array) $methods;
7334 $this->
action = $this->parseAction($action);
7335 if (in_array(
'GET', $this->methods) && !in_array(
'HEAD', $this->methods)) {
7336 $this->methods[] =
'HEAD';
7338 if (isset($this->
action[
'prefix'])) {
7339 $this->prefix($this->
action[
'prefix']);
7344 $this->container = $this->container ?:
new Container();
7346 if (!is_string($this->
action[
'uses'])) {
7347 return $this->runCallable($request);
7349 if ($this->customDispatcherIsBound()) {
7350 return $this->runWithCustomDispatcher($request);
7352 return $this->runController($request);
7359 $parameters = $this->resolveMethodDependencies($this->parametersWithoutNulls(),
new ReflectionFunction($this->
action[
'uses']));
7360 return call_user_func_array($this->
action[
'uses'], $parameters);
7364 list($class, $method) = explode(
'@', $this->
action[
'uses']);
7365 $parameters = $this->resolveClassMethodDependencies($this->parametersWithoutNulls(), $class, $method);
7366 if (!method_exists($instance = $this->container->make($class), $method)) {
7369 return call_user_func_array(array($instance, $method), $parameters);
7373 return $this->container->bound(
'illuminate.route.dispatcher');
7377 list($class, $method) = explode(
'@', $this->
action[
'uses']);
7378 $dispatcher = $this->container->make(
'illuminate.route.dispatcher');
7379 return $dispatcher->dispatch($this, $request, $class, $method);
7383 $this->compileRoute();
7384 foreach ($this->getValidators() as $validator) {
7388 if (!$validator->matches($this, $request)) {
7396 $optionals = $this->extractOptionalParameters();
7397 $uri = preg_replace(
'/\\{(\\w+?)\\?\\}/',
'{$1}', $this->uri);
7398 $this->compiled = with(
new SymfonyRoute(
$uri, $optionals, $this->wheres, array(), $this->domain() ?:
''))->compile();
7402 preg_match_all(
'/\\{(\\w+?)\\?\\}/', $this->uri, $matches);
7403 return isset($matches[1]) ? array_fill_keys($matches[1], null) : array();
7407 return (array) array_get($this->
action,
'middleware', array());
7411 if (!isset($this->
action[
'before'])) {
7414 return $this->parseFilters($this->
action[
'before']);
7418 if (!isset($this->
action[
'after'])) {
7421 return $this->parseFilters($this->
action[
'after']);
7425 return array_build(static::explodeFilters($filters),
function ($key, $value) {
7426 return Route::parseFilter($value);
7431 if (is_array($filters)) {
7432 return static::explodeArrayFilters($filters);
7434 return array_map(
'trim', explode(
'|', $filters));
7439 foreach ($filters as
$filter) {
7440 $results = array_merge($results, array_map(
'trim', explode(
'|', $filter)));
7446 if (!str_contains(
$filter,
':')) {
7447 return array(
$filter, array());
7449 return static::parseParameterFilter(
$filter);
7453 list($name, $parameters) = explode(
':',
$filter, 2);
7454 return array($name, explode(
',', $parameters));
7458 return array_key_exists($name, $this->parameters());
7462 return $this->parameter($name, $default);
7466 return array_get($this->parameters(), $name, $default);
7470 $this->parameters();
7471 $this->parameters[$name] = $value;
7475 $this->parameters();
7476 unset($this->parameters[$name]);
7480 if (isset($this->parameters)) {
7481 return array_map(
function ($value) {
7482 return is_string($value) ? rawurldecode($value) : $value;
7483 }, $this->parameters);
7485 throw new LogicException(
'Route is not bound.');
7489 return array_filter($this->parameters(),
function ($p) {
7490 return !is_null($p);
7495 if (isset($this->parameterNames)) {
7496 return $this->parameterNames;
7498 return $this->parameterNames = $this->compileParameterNames();
7502 preg_match_all(
'/\\{(.*?)\\}/', $this->domain() . $this->uri, $matches);
7503 return array_map(
function ($m) {
7504 return trim($m,
'?');
7509 $this->compileRoute();
7510 $this->bindParameters($request);
7515 $params = $this->matchToKeys(array_slice($this->bindPathParameters($request), 1));
7516 if (!is_null($this->compiled->getHostRegex())) {
7517 $params = $this->bindHostParameters($request, $params);
7519 return $this->parameters = $this->replaceDefaults($params);
7523 preg_match($this->compiled->getRegex(),
'/' . $request->
decodedPath(), $matches);
7528 preg_match($this->compiled->getHostRegex(), $request->
getHost(), $matches);
7529 return array_merge($this->matchToKeys(array_slice($matches, 1)), $parameters);
7533 if (count($this->parameterNames()) == 0) {
7536 $parameters = array_intersect_key($matches, array_flip($this->parameterNames()));
7537 return array_filter($parameters,
function ($value) {
7538 return is_string($value) && strlen($value) > 0;
7543 foreach ($parameters as $key => &$value) {
7544 $value = isset($value) ? $value : array_get($this->defaults, $key);
7550 if (is_callable($action)) {
7551 return array(
'uses' => $action);
7552 } elseif (!isset($action[
'uses'])) {
7553 $action[
'uses'] = $this->findCallable($action);
7559 return array_first($action,
function ($key, $value) {
7560 return is_callable($value);
7565 if (isset(static::$validators)) {
7566 return static::$validators;
7572 return $this->addFilters(
'before', $filters);
7576 return $this->addFilters(
'after', $filters);
7580 $filters = static::explodeFilters($filters);
7581 if (isset($this->
action[$type])) {
7582 $existing = static::explodeFilters($this->
action[$type]);
7583 $this->
action[$type] = array_merge($existing, $filters);
7585 $this->
action[$type] = $filters;
7591 $this->defaults[$key] = $value;
7594 public function where($name, $expression = null)
7596 foreach ($this->parseWhere($name, $expression) as $name => $expression) {
7597 $this->wheres[$name] = $expression;
7603 return is_array($name) ? $name : array($name => $expression);
7607 foreach ($wheres as $name => $expression) {
7608 $this->where($name, $expression);
7614 $this->uri = trim($prefix,
'/') .
'/' . trim($this->uri,
'/');
7619 return $this->uri();
7627 return $this->methods();
7631 return $this->methods;
7635 return in_array(
'http', $this->
action,
true);
7639 return $this->secure();
7643 return in_array(
'https', $this->
action,
true);
7647 return isset($this->
action[
'domain']) ? $this->
action[
'domain'] : null;
7660 return isset($this->
action[
'prefix']) ? $this->
action[
'prefix'] : null;
7664 return isset($this->
action[
'as']) ? $this->
action[
'as'] : null;
7668 return isset($this->
action[
'controller']) ? $this->
action[
'controller'] :
'Closure';
7672 return $this->action;
7681 return $this->compiled;
7690 if ($this->
action[
'uses'] instanceof Closure) {
7691 throw new LogicException(
"Unable to prepare route [{$this->uri}] for serialization. Uses Closure.");
7693 unset($this->container);
7694 unset($this->compiled);
7698 return $this->parameter($key);
7712 protected $routes = array();
7713 protected $allRoutes = array();
7714 protected $nameList = array();
7715 protected $actionList = array();
7718 $this->addToCollections($route);
7719 $this->addLookups($route);
7724 $domainAndUri = $route->domain() . $route->getUri();
7725 foreach ($route->methods() as $method) {
7726 $this->routes[$method][$domainAndUri] = $route;
7728 $this->allRoutes[$method . $domainAndUri] = $route;
7732 $action = $route->getAction();
7733 if (isset($action[
'as'])) {
7734 $this->nameList[$action[
'as']] = $route;
7736 if (isset($action[
'controller'])) {
7737 $this->addToActionList($action, $route);
7742 $this->actionList[$action[
'controller']] = $route;
7746 $routes = $this->
get($request->
getMethod());
7747 $route = $this->check($routes, $request);
7748 if (!is_null($route)) {
7749 return $route->bind($request);
7751 $others = $this->checkForAlternateVerbs($request);
7752 if (count($others) > 0) {
7753 return $this->getRouteForMethods($request, $others);
7759 $methods = array_diff(Router::$verbs, array($request->getMethod()));
7761 foreach ($methods as $method) {
7762 if (!is_null($this->check($this->
get($method), $request,
false))) {
7763 $others[] = $method;
7770 if ($request->method() ==
'OPTIONS') {
7771 return (
new Route(
'OPTIONS', $request->path(),
function () use($methods) {
7772 return new Response(
'', 200, array(
'Allow' => implode(
',', $methods)));
7773 }))->bind($request);
7775 $this->methodNotAllowed($methods);
7781 protected function check(array $routes, $request, $includingMethod =
true)
7783 return array_first($routes,
function ($key, $value) use($request, $includingMethod) {
7784 return $value->matches($request, $includingMethod);
7787 protected function get($method = null)
7789 if (is_null($method)) {
7790 return $this->getRoutes();
7792 return array_get($this->routes, $method, array());
7796 return !is_null($this->getByName($name));
7800 return isset($this->nameList[$name]) ? $this->nameList[$name] : null;
7804 return isset($this->actionList[$action]) ? $this->actionList[$action] : null;
7808 return array_values($this->allRoutes);
7812 return new ArrayIterator($this->getRoutes());
7816 return count($this->getRoutes());
7825 private $staticPrefix;
7827 private $pathVariables;
7828 private $hostVariables;
7830 private $hostTokens;
7831 public function __construct($staticPrefix, $regex, array $tokens, array $pathVariables, $hostRegex = null, array $hostTokens = array(), array $hostVariables = array(), array $variables = array())
7833 $this->staticPrefix = (string) $staticPrefix;
7834 $this->
regex = $regex;
7835 $this->tokens = $tokens;
7836 $this->pathVariables = $pathVariables;
7837 $this->hostRegex = $hostRegex;
7838 $this->hostTokens = $hostTokens;
7839 $this->hostVariables = $hostVariables;
7840 $this->variables = $variables;
7844 return serialize(array(
'vars' => $this->variables,
'path_prefix' => $this->staticPrefix,
'path_regex' => $this->
regex,
'path_tokens' => $this->tokens,
'path_vars' => $this->pathVariables,
'host_regex' => $this->hostRegex,
'host_tokens' => $this->hostTokens,
'host_vars' => $this->hostVariables));
7848 $data = unserialize($serialized);
7849 $this->variables = $data[
'vars'];
7850 $this->staticPrefix = $data[
'path_prefix'];
7851 $this->
regex = $data[
'path_regex'];
7852 $this->tokens = $data[
'path_tokens'];
7853 $this->pathVariables = $data[
'path_vars'];
7854 $this->hostRegex = $data[
'host_regex'];
7855 $this->hostTokens = $data[
'host_tokens'];
7856 $this->hostVariables = $data[
'host_vars'];
7860 return $this->staticPrefix;
7864 return $this->regex;
7868 return $this->hostRegex;
7872 return $this->tokens;
7876 return $this->hostTokens;
7880 return $this->variables;
7884 return $this->pathVariables;
7888 return $this->hostVariables;
7895 public static function compile(
Route $route);
7901 const REGEX_DELIMITER =
'#';
7902 const SEPARATORS =
'/,;.:-_~+*=@|';
7905 $hostVariables = array();
7906 $variables = array();
7908 $hostTokens = array();
7909 if (
'' !== ($host = $route->
getHost())) {
7910 $result = self::compilePattern($route, $host,
true);
7911 $hostVariables = $result[
'variables'];
7912 $variables = $hostVariables;
7913 $hostTokens = $result[
'tokens'];
7914 $hostRegex = $result[
'regex'];
7917 $result = self::compilePattern($route,
$path,
false);
7918 $staticPrefix = $result[
'staticPrefix'];
7919 $pathVariables = $result[
'variables'];
7920 $variables = array_merge($variables, $pathVariables);
7921 $tokens = $result[
'tokens'];
7922 $regex = $result[
'regex'];
7923 return new CompiledRoute($staticPrefix, $regex, $tokens, $pathVariables, $hostRegex, $hostTokens, $hostVariables, array_unique($variables));
7925 private static function compilePattern(
Route $route, $pattern, $isHost)
7928 $variables = array();
7931 $defaultSeparator = $isHost ?
'.' :
'/';
7932 preg_match_all(
'#\\{\\w+\\}#', $pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
7933 foreach ($matches as $match) {
7934 $varName = substr($match[0][0], 1, -1);
7935 $precedingText = substr($pattern, $pos, $match[0][1] - $pos);
7936 $pos = $match[0][1] + strlen($match[0][0]);
7937 $precedingChar = strlen($precedingText) > 0 ? substr($precedingText, -1) :
'';
7938 $isSeparator =
'' !== $precedingChar &&
false !== strpos(static::SEPARATORS, $precedingChar);
7939 if (is_numeric($varName)) {
7940 throw new \DomainException(sprintf(
'Variable name "%s" cannot be numeric in route pattern "%s". Please use a different name.', $varName, $pattern));
7942 if (in_array($varName, $variables)) {
7943 throw new \LogicException(sprintf(
'Route pattern "%s" cannot reference variable name "%s" more than once.', $pattern, $varName));
7945 if ($isSeparator && strlen($precedingText) > 1) {
7946 $tokens[] = array(
'text', substr($precedingText, 0, -1));
7947 } elseif (!$isSeparator && strlen($precedingText) > 0) {
7948 $tokens[] = array(
'text', $precedingText);
7951 if (null === $regexp) {
7952 $followingPattern = (string) substr($pattern, $pos);
7953 $nextSeparator = self::findNextSeparator($followingPattern);
7954 $regexp = sprintf(
'[^%s%s]+', preg_quote($defaultSeparator, self::REGEX_DELIMITER), $defaultSeparator !== $nextSeparator &&
'' !== $nextSeparator ? preg_quote($nextSeparator, self::REGEX_DELIMITER) :
'');
7955 if (
'' !== $nextSeparator && !preg_match(
'#^\\{\\w+\\}#', $followingPattern) ||
'' === $followingPattern) {
7959 $tokens[] = array(
'variable', $isSeparator ? $precedingChar :
'', $regexp, $varName);
7960 $variables[] = $varName;
7962 if ($pos < strlen($pattern)) {
7963 $tokens[] = array(
'text', substr($pattern, $pos));
7965 $firstOptional = PHP_INT_MAX;
7967 for (
$i = count($tokens) - 1;
$i >= 0;
$i--) {
7968 $token = $tokens[
$i];
7969 if (
'variable' === $token[0] && $route->
hasDefault($token[3])) {
7970 $firstOptional =
$i;
7977 for (
$i = 0, $nbToken = count($tokens);
$i < $nbToken;
$i++) {
7978 $regexp .= self::computeRegexp($tokens,
$i, $firstOptional);
7980 return array(
'staticPrefix' =>
'text' === $tokens[0][0] ? $tokens[0][1] :
'',
'regex' => self::REGEX_DELIMITER .
'^' . $regexp .
'$' . self::REGEX_DELIMITER .
's' . ($isHost ?
'i' :
''),
'tokens' => array_reverse($tokens),
'variables' => $variables);
7982 private static function findNextSeparator($pattern)
7984 if (
'' == $pattern) {
7987 $pattern = preg_replace(
'#\\{\\w+\\}#',
'', $pattern);
7988 return isset($pattern[0]) &&
false !== strpos(static::SEPARATORS, $pattern[0]) ? $pattern[0] :
'';
7990 private static function computeRegexp(array $tokens, $index, $firstOptional)
7992 $token = $tokens[$index];
7993 if (
'text' === $token[0]) {
7994 return preg_quote($token[1], self::REGEX_DELIMITER);
7996 if (0 === $index && 0 === $firstOptional) {
7997 return sprintf(
'%s(?P<%s>%s)?', preg_quote($token[1], self::REGEX_DELIMITER), $token[3], $token[2]);
7999 $regexp = sprintf(
'%s(?P<%s>%s)', preg_quote($token[1], self::REGEX_DELIMITER), $token[3], $token[2]);
8000 if ($index >= $firstOptional) {
8001 $regexp =
"(?:{$regexp}";
8002 $nbTokens = count($tokens);
8003 if ($nbTokens - 1 == $index) {
8004 $regexp .= str_repeat(
')?', $nbTokens - $firstOptional - (0 === $firstOptional ? 1 : 0));
8016 private $path =
'/';
8018 private $schemes = array();
8019 private $methods = array();
8020 private $defaults = array();
8021 private $requirements = array();
8022 private $options = array();
8024 private $condition =
'';
8025 public function __construct(
$path, array $defaults = array(), array $requirements = array(), array $options = array(), $host =
'', $schemes = array(), $methods = array(), $condition =
'')
8027 $this->setPath(
$path);
8028 $this->setDefaults($defaults);
8029 $this->setRequirements($requirements);
8030 $this->setOptions($options);
8031 $this->setHost($host);
8033 $this->setSchemes($schemes);
8036 $this->setMethods($methods);
8038 $this->setCondition($condition);
8042 return serialize(array(
'path' => $this->
path,
'host' => $this->host,
'defaults' => $this->defaults,
'requirements' => $this->requirements,
'options' => $this->
options,
'schemes' => $this->schemes,
'methods' => $this->methods,
'condition' => $this->condition,
'compiled' => $this->compiled));
8046 $data = unserialize($serialized);
8047 $this->
path = $data[
'path'];
8048 $this->host = $data[
'host'];
8049 $this->defaults = $data[
'defaults'];
8050 $this->requirements = $data[
'requirements'];
8051 $this->
options = $data[
'options'];
8052 $this->schemes = $data[
'schemes'];
8053 $this->methods = $data[
'methods'];
8054 if (isset($data[
'condition'])) {
8055 $this->condition = $data[
'condition'];
8057 if (isset($data[
'compiled'])) {
8058 $this->compiled = $data[
'compiled'];
8067 return $this->setPath($pattern);
8075 $this->
path =
'/' . ltrim(trim($pattern),
'/');
8076 $this->compiled = null;
8085 $this->host = (string) $pattern;
8086 $this->compiled = null;
8091 return $this->schemes;
8095 $this->schemes = array_map(
'strtolower', (array) $schemes);
8096 if ($this->schemes) {
8097 $this->requirements[
'_scheme'] = implode(
'|', $this->schemes);
8099 unset($this->requirements[
'_scheme']);
8101 $this->compiled = null;
8106 return in_array(strtolower($scheme), $this->schemes,
true);
8110 return $this->methods;
8114 $this->methods = array_map(
'strtoupper', (array) $methods);
8115 if ($this->methods) {
8116 $this->requirements[
'_method'] = implode(
'|', $this->methods);
8118 unset($this->requirements[
'_method']);
8120 $this->compiled = null;
8129 $this->
options = array(
'compiler_class' =>
'Symfony\\Component\\Routing\\RouteCompiler');
8130 return $this->addOptions($options);
8134 foreach ($options as $name => $option) {
8135 $this->
options[$name] = $option;
8137 $this->compiled = null;
8142 $this->
options[$name] = $value;
8143 $this->compiled = null;
8148 return isset($this->
options[$name]) ? $this->
options[$name] : null;
8152 return array_key_exists($name, $this->
options);
8156 return $this->defaults;
8160 $this->defaults = array();
8161 return $this->addDefaults($defaults);
8165 foreach ($defaults as $name => $default) {
8166 $this->defaults[$name] = $default;
8168 $this->compiled = null;
8173 return isset($this->defaults[$name]) ? $this->defaults[$name] : null;
8177 return array_key_exists($name, $this->defaults);
8181 $this->defaults[$name] = $default;
8182 $this->compiled = null;
8187 return $this->requirements;
8191 $this->requirements = array();
8192 return $this->addRequirements($requirements);
8196 foreach ($requirements as $key => $regex) {
8197 $this->requirements[$key] = $this->sanitizeRequirement($key, $regex);
8199 $this->compiled = null;
8204 return isset($this->requirements[$key]) ? $this->requirements[$key] : null;
8208 return array_key_exists($key, $this->requirements);
8212 $this->requirements[$key] = $this->sanitizeRequirement($key, $regex);
8213 $this->compiled = null;
8218 return $this->condition;
8222 $this->condition = (string) $condition;
8223 $this->compiled = null;
8228 if (null !== $this->compiled) {
8229 return $this->compiled;
8231 $class = $this->getOption(
'compiler_class');
8232 return $this->compiled = $class::compile($this);
8234 private function sanitizeRequirement($key, $regex)
8236 if (!is_string($regex)) {
8237 throw new \InvalidArgumentException(sprintf(
'Routing requirement for "%s" must be a string.', $key));
8239 if (
'' !== $regex &&
'^' === $regex[0]) {
8240 $regex = (string) substr($regex, 1);
8242 if (
'$' === substr($regex, -1)) {
8243 $regex = substr($regex, 0, -1);
8245 if (
'' === $regex) {
8246 throw new \InvalidArgumentException(sprintf(
'Routing requirement for "%s" cannot be empty.', $key));
8248 if (
'_scheme' === $key) {
8249 $this->setSchemes(explode(
'|', $regex));
8250 } elseif (
'_method' === $key) {
8251 $this->setMethods(explode(
'|', $regex));
8259 use BadMethodCallException;
8260 use InvalidArgumentException;
8264 protected $middleware = array();
8265 protected $beforeFilters = array();
8266 protected $afterFilters = array();
8268 public function middleware($middleware, array $options = array())
8270 $this->middleware[$middleware] =
$options;
8274 $this->beforeFilters[] = $this->parseFilter(
$filter, $options);
8278 $this->afterFilters[] = $this->parseFilter(
$filter, $options);
8282 $parameters = array();
8284 if (
$filter instanceof Closure) {
8286 } elseif ($this->isInstanceFilter(
$filter)) {
8291 return compact(
'original',
'filter',
'parameters',
'options');
8295 $this->getRouter()->filter($name = spl_object_hash($filter), $filter);
8300 $this->getRouter()->filter(
$filter, array($this, substr(
$filter, 1)));
8306 if (method_exists($this, substr(
$filter, 1))) {
8309 throw new InvalidArgumentException(
"Filter method [{$filter}] does not exist.");
8315 $this->beforeFilters = $this->removeFilter(
$filter, $this->getBeforeFilters());
8319 $this->afterFilters = $this->removeFilter(
$filter, $this->getAfterFilters());
8323 return array_filter($current,
function (
$filter) use($removing) {
8324 return $filter[
'original'] != $removing;
8329 return $this->middleware;
8333 return $this->beforeFilters;
8337 return $this->afterFilters;
8341 return static::$router;
8345 static::$router = $router;
8349 return call_user_func_array(array($this, $method), $parameters);
8357 throw new BadMethodCallException(
"Method [{$method}] does not exist.");
8373 $this->router = $router;
8378 $instance = $this->makeController($controller);
8379 $this->assignAfter($instance, $route, $request, $method);
8380 $response = $this->before($instance, $route, $request, $method);
8382 $response = $this->callWithinStack($instance, $route, $request, $method);
8389 return $this->container->make($controller);
8393 $middleware = $this->getMiddleware($instance, $method);
8394 return (
new Pipeline($this->container))->send($request)->through($middleware)->then(
function ($request) use($instance, $route, $method) {
8395 return $this->
call($instance, $route, $method);
8400 $middleware = $this->router->getMiddleware();
8402 foreach ($instance->getMiddleware() as $name =>
$options) {
8403 if (!$this->methodExcludedByOptions($method, $options)) {
8404 $results[] = array_get($middleware, $name, $name);
8411 return !
empty($options[
'only']) && !in_array($method, (array) $options[
'only']) || !
empty($options[
'except']) && in_array($method, (array) $options[
'except']);
8413 protected function call($instance, $route, $method)
8415 $parameters = $this->resolveClassMethodDependencies($route->parametersWithoutNulls(), $instance, $method);
8416 return $instance->callAction($method, $parameters);
8418 protected function before($instance, $route, $request, $method)
8420 foreach ($instance->getBeforeFilters() as
$filter) {
8421 if ($this->filterApplies(
$filter, $request, $method)) {
8431 foreach ($instance->getAfterFilters() as
$filter) {
8432 if ($this->filterApplies(
$filter, $request, $method)) {
8433 $route->after($this->getAssignableAfter(
$filter));
8439 if (
$filter[
'original'] instanceof Closure) {
8446 foreach (array(
'Method',
'On') as $type) {
8447 if ($this->{
"filterFails{$type}"}(
$filter, $request, $method)) {
8455 return $this->methodExcludedByOptions($method,
$filter[
'options']);
8459 $on = array_get(
$filter,
'options.on');
8463 if (is_string($on)) {
8464 $on = explode(
'|', $on);
8466 return !in_array(strtolower($request->getMethod()), $on);
8470 return $this->router->callRouteFilter(
$filter[
'filter'],
$filter[
'parameters'], $route, $request);
8476 use ReflectionMethod;
8479 protected $verbs = array(
'any',
'get',
'post',
'put',
'patch',
'delete',
'head',
'options');
8482 $routable = array();
8483 $reflection =
new ReflectionClass($controller);
8484 $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC);
8485 foreach ($methods as $method) {
8486 if ($this->isRoutable($method)) {
8487 $data = $this->getMethodData($method, $prefix);
8488 $routable[$method->name][] = $data;
8489 if ($data[
'plain'] == $prefix .
'/index') {
8490 $routable[$method->name][] = $this->getIndexData($data, $prefix);
8498 if ($method->class ==
'Illuminate\\Routing\\Controller') {
8501 return starts_with($method->name, $this->verbs);
8505 $verb = $this->getVerb($name = $method->name);
8506 $uri = $this->addUriWildcards($plain = $this->getPlainUri($name, $prefix));
8507 return compact(
'verb',
'plain',
'uri');
8511 return array(
'verb' => $data[
'verb'],
'plain' => $prefix,
'uri' => $prefix);
8515 return head(explode(
'_', snake_case($name)));
8519 return $prefix .
'/' . implode(
'-', array_slice(explode(
'_', snake_case($name)), 1));
8523 return $uri .
'/{one?}/{two?}/{three?}/{four?}/{five?}';
8529 use InvalidArgumentException;
8542 protected $dontEncode = array(
'%2F' =>
'/',
'%40' =>
'@',
'%3A' =>
':',
'%3B' =>
';',
'%2C' =>
',',
'%3D' =>
'=',
'%2B' =>
'+',
'%21' =>
'!',
'%2A' =>
'*',
'%7C' =>
'|',
'%3F' =>
'?',
'%26' =>
'&',
'%23' =>
'#',
'%25' =>
'%');
8545 $this->routes = $routes;
8546 $this->setRequest($request);
8550 return $this->request->fullUrl();
8554 return $this->
to($this->request->getPathInfo());
8558 $referrer = $this->request->headers->get(
'referer');
8559 $url = $referrer ? $this->
to($referrer) : $this->getPreviousUrlFromSession();
8560 return $url ?: $this->
to(
'/');
8562 public function to(
$path, $extra = array(), $secure = null)
8564 if ($this->isValidUrl(
$path)) {
8567 $scheme = $this->getScheme($secure);
8568 $extra = $this->formatParameters($extra);
8569 $tail = implode(
'/', array_map(
'rawurlencode', (array) $extra));
8570 $root = $this->getRootUrl($scheme);
8571 return $this->trimUrl($root,
$path, $tail);
8575 return $this->
to(
$path, $parameters,
true);
8579 if ($this->isValidUrl(
$path)) {
8582 $root = $this->getRootUrl($this->getScheme($secure));
8583 return $this->removeIndex($root) .
'/' . trim(
$path,
'/');
8588 return str_contains($root,
$i) ? str_replace(
'/' .
$i,
'', $root) : $root;
8592 return $this->asset(
$path,
true);
8596 if (is_null($secure)) {
8597 if (is_null($this->cachedSchema)) {
8598 $this->cachedSchema = $this->forceSchema ?: $this->request->getScheme() .
'://';
8600 return $this->cachedSchema;
8602 return $secure ?
'https://' :
'http://';
8606 $this->cachedSchema = null;
8607 $this->forceSchema = $schema .
'://';
8609 public function route($name, $parameters = array(), $absolute =
true)
8611 if (!is_null($route = $this->routes->getByName($name))) {
8612 return $this->toRoute($route, $parameters, $absolute);
8614 throw new InvalidArgumentException(
"Route [{$name}] not defined.");
8616 protected function toRoute($route, $parameters, $absolute)
8618 $parameters = $this->formatParameters($parameters);
8619 $domain = $this->getRouteDomain($route, $parameters);
8620 $uri = strtr(rawurlencode($this->addQueryString($this->trimUrl($root = $this->replaceRoot($route, $domain, $parameters), $this->replaceRouteParameters($route->uri(), $parameters)), $parameters)), $this->dontEncode);
8621 return $absolute ?
$uri :
'/' . ltrim(str_replace($root,
'',
$uri),
'/');
8625 return $this->replaceRouteParameters($this->getRouteRoot($route, $domain), $parameters);
8629 if (count($parameters)) {
8630 $path = preg_replace_sub(
'/\\{.*?\\}/', $parameters, $this->replaceNamedParameters(
$path, $parameters));
8632 return trim(preg_replace(
'/\\{.*?\\?\\}/',
'',
$path),
'/');
8636 return preg_replace_callback(
'/\\{(.*?)\\??\\}/',
function ($m) use(&$parameters) {
8637 return isset($parameters[$m[1]]) ? array_pull($parameters, $m[1]) : $m[0];
8642 if (!is_null($fragment = parse_url(
$uri, PHP_URL_FRAGMENT))) {
8643 $uri = preg_replace(
'/#.*/',
'',
$uri);
8645 $uri .= $this->getRouteQueryString($parameters);
8646 return is_null($fragment) ?
$uri :
$uri .
"#{$fragment}";
8650 return $this->replaceRoutableParameters($parameters);
8654 $parameters = is_array($parameters) ? $parameters : array($parameters);
8655 foreach ($parameters as $key => $parameter) {
8657 $parameters[$key] = $parameter->getRouteKey();
8664 if (count($parameters) == 0) {
8667 $query = http_build_query($keyed = $this->getStringParameters($parameters));
8668 if (count($keyed) < count($parameters)) {
8669 $query .=
'&' . implode(
'&', $this->getNumericParameters($parameters));
8671 return '?' . trim($query,
'&');
8675 return array_where($parameters,
function ($k, $v) {
8676 return is_string($k);
8681 return array_where($parameters,
function ($k, $v) {
8682 return is_numeric($k);
8687 return $route->domain() ? $this->formatDomain($route, $parameters) : null;
8691 return $this->addPortToDomain($this->getDomainAndScheme($route));
8695 return $this->getRouteScheme($route) . $route->domain();
8699 if (in_array($this->request->getPort(), array(
'80',
'443'))) {
8702 return $domain .
':' . $this->request->getPort();
8706 return $this->getRootUrl($this->getRouteScheme($route), $domain);
8710 if ($route->httpOnly()) {
8711 return $this->getScheme(
false);
8712 } elseif ($route->httpsOnly()) {
8713 return $this->getScheme(
true);
8715 return $this->getScheme(null);
8717 public function action($action, $parameters = array(), $absolute =
true)
8719 if ($this->rootNamespace && !(strpos($action,
'\\') === 0)) {
8720 $action = $this->rootNamespace .
'\\' . $action;
8722 $action = trim($action,
'\\');
8724 if (!is_null($route = $this->routes->getByAction($action))) {
8725 return $this->toRoute($route, $parameters, $absolute);
8727 throw new InvalidArgumentException(
"Action {$action} not defined.");
8731 if (is_null($root)) {
8732 if (is_null($this->cachedRoot)) {
8733 $this->cachedRoot = $this->forcedRoot ?: $this->request->root();
8735 $root = $this->cachedRoot;
8737 $start = starts_with($root,
'http://') ?
'http://' :
'https://';
8738 return preg_replace(
'~' .
$start .
'~', $scheme, $root, 1);
8742 $this->forcedRoot = rtrim($root,
'/');
8743 $this->cachedRoot = null;
8747 if (starts_with(
$path, array(
'#',
'//',
'mailto:',
'tel:',
'http://',
'https://'))) {
8750 return filter_var(
$path, FILTER_VALIDATE_URL) !==
false;
8754 return trim($root .
'/' . trim(
$path .
'/' . $tail,
'/'),
'/');
8758 return $this->request;
8762 $this->request = $request;
8763 $this->cachedRoot = null;
8764 $this->cachedSchema = null;
8768 $this->routes = $routes;
8773 $session = $this->getSession();
8774 return $session ? $session->previousUrl() : null;
8778 return call_user_func($this->sessionResolver ?:
function () {
8783 $this->sessionResolver = $sessionResolver;
8788 $this->rootNamespace = $rootNamespace;
8797 protected $defer =
true;
8798 public function register()
8800 $this->app->singleton(
'Illuminate\\Bus\\Dispatcher',
function (
$app) {
8802 return $app[
'Illuminate\\Contracts\\Queue\\Queue'];
8805 $this->app->alias(
'Illuminate\\Bus\\Dispatcher',
'Illuminate\\Contracts\\Bus\\Dispatcher');
8806 $this->app->alias(
'Illuminate\\Bus\\Dispatcher',
'Illuminate\\Contracts\\Bus\\QueueingDispatcher');
8810 return array(
'Illuminate\\Bus\\Dispatcher',
'Illuminate\\Contracts\\Bus\\Dispatcher',
'Illuminate\\Contracts\\Bus\\QueueingDispatcher');
8817 use ReflectionClass;
8832 protected $pipes = array();
8834 protected $mappings = array();
8839 $this->queueResolver = $queueResolver;
8840 $this->pipeline =
new Pipeline($container);
8844 return $this->
dispatch($this->marshalFromArray($command, $array));
8846 public function dispatchFrom($command, ArrayAccess $source, array $extras = array())
8848 return $this->
dispatch($this->marshal($command, $source, $extras));
8852 return $this->marshal($command,
new Collection(), $array);
8854 protected function marshal($command, ArrayAccess $source, array $extras = array())
8856 $injected = array();
8857 $reflection =
new ReflectionClass($command);
8858 if ($constructor = $reflection->getConstructor()) {
8859 $injected = array_map(
function ($parameter) use($command, $source, $extras) {
8860 return $this->getParameterValueForCommand($command, $source, $parameter, $extras);
8861 }, $constructor->getParameters());
8863 return $reflection->newInstanceArgs($injected);
8867 if (array_key_exists($parameter->name, $extras)) {
8868 return $extras[$parameter->name];
8870 if (isset($source[$parameter->name])) {
8871 return $source[$parameter->name];
8873 if ($parameter->isDefaultValueAvailable()) {
8874 return $parameter->getDefaultValue();
8876 MarshalException::whileMapping($command, $parameter);
8878 public function dispatch($command, Closure $afterResolving = null)
8880 if ($this->queueResolver && $this->commandShouldBeQueued($command)) {
8881 return $this->dispatchToQueue($command);
8883 return $this->dispatchNow($command, $afterResolving);
8888 return $this->pipeline->send($command)->through($this->pipes)->then(
function ($command) use($afterResolving) {
8890 return $this->container->call(array($command,
'handle'));
8892 $handler = $this->resolveHandler($command);
8893 if ($afterResolving) {
8894 call_user_func($afterResolving, $handler);
8896 return call_user_func(array($handler, $this->getHandlerMethod($command)), $command);
8904 return (
new ReflectionClass($this->getHandlerClass($command)))->implementsInterface(
'Illuminate\\Contracts\\Queue\\ShouldBeQueued');
8908 $queue = call_user_func($this->queueResolver);
8909 if (!$queue instanceof
Queue) {
8910 throw new \RuntimeException(
'Queue resolver did not return a Queue implementation.');
8912 if (method_exists($command,
'queue')) {
8913 $command->queue($queue, $command);
8915 $queue->push($command);
8923 return $this->container->make($this->getHandlerClass($command));
8928 return get_class($command);
8930 return $this->inflectSegment($command, 0);
8937 return $this->inflectSegment($command, 1);
8941 $className = get_class($command);
8942 if (isset($this->mappings[$className])) {
8943 return $this->getMappingSegment($className, $segment);
8944 } elseif ($this->mapper) {
8945 return $this->getMapperSegment($command, $segment);
8947 throw new \InvalidArgumentException(
"No handler registered for command [{$className}]");
8951 return explode(
'@', $this->mappings[$className])[$segment];
8955 return explode(
'@', call_user_func($this->mapper, $command))[$segment];
8957 public function maps(array $commands)
8959 $this->mappings = array_merge($this->mappings, $commands);
8963 $this->mapper = $mapper;
8965 public static function simpleMapping($command, $commandNamespace, $handlerNamespace)
8967 $command = str_replace($commandNamespace,
'', get_class($command));
8968 return $handlerNamespace .
'\\' . trim($command,
'\\') .
'Handler@handle';
8972 $this->pipes = $pipes;
8985 protected $pipes = array();
8986 protected $method =
'handle';
8993 $this->passable = $passable;
8998 $this->pipes = is_array($pipes) ? $pipes : func_get_args();
9003 $this->method = $method;
9006 public function then(Closure $destination)
9008 $firstSlice = $this->getInitialSlice($destination);
9009 $pipes = array_reverse($this->pipes);
9010 return call_user_func(array_reduce($pipes, $this->getSlice(), $firstSlice), $this->passable);
9014 return function ($stack, $pipe) {
9015 return function ($passable) use($stack, $pipe) {
9016 if ($pipe instanceof Closure) {
9017 return call_user_func($pipe, $passable, $stack);
9019 return $this->container->make($pipe)->{$this->method}($passable, $stack);
9026 return function ($passable) use($destination) {
9027 return call_user_func($destination, $passable);
9047 if (is_null($route->
getCompiled()->getHostRegex())) {
9073 return !$request->
secure();
9074 } elseif ($route->
secure()) {
9075 return $request->
secure();
9088 $path = $request->
path() ==
'/' ?
'/' :
'/' . $request->
path();
9095 use ReflectionClass;
9102 protected $listeners = array();
9103 protected $wildcards = array();
9104 protected $sorted = array();
9105 protected $firing = array();
9111 public function listen($events, $listener, $priority = 0)
9113 foreach ((array) $events as $event) {
9114 if (str_contains($event,
'*')) {
9115 $this->setupWildcardListen($event, $listener);
9117 $this->listeners[$event][$priority][] = $this->makeListener($listener);
9118 unset($this->sorted[$event]);
9124 $this->wildcards[$event][] = $this->makeListener($listener);
9128 return isset($this->listeners[$eventName]);
9130 public function push($event, $payload = array())
9132 $this->listen($event .
'_pushed',
function () use($event, $payload) {
9133 $this->fire($event, $payload);
9138 $subscriber = $this->resolveSubscriber($subscriber);
9139 $subscriber->subscribe($this);
9143 if (is_string($subscriber)) {
9144 return $this->container->make($subscriber);
9148 public function until($event, $payload = array())
9150 return $this->fire($event, $payload,
true);
9154 $this->fire($event .
'_pushed');
9158 return last($this->firing);
9160 public function fire($event, $payload = array(), $halt =
false)
9162 if (is_object($event)) {
9163 list($payload, $event) = array(array($event), get_class($event));
9165 $responses = array();
9166 if (!is_array($payload)) {
9167 $payload = array($payload);
9169 $this->firing[] = $event;
9170 foreach ($this->getListeners($event) as $listener) {
9171 $response = call_user_func_array($listener, $payload);
9173 array_pop($this->firing);
9181 array_pop($this->firing);
9182 return $halt ? null : $responses;
9186 $wildcards = $this->getWildcardListeners($eventName);
9187 if (!isset($this->sorted[$eventName])) {
9188 $this->sortListeners($eventName);
9190 return array_merge($this->sorted[$eventName], $wildcards);
9194 $wildcards = array();
9195 foreach ($this->wildcards as $key => $listeners) {
9196 if (str_is($key, $eventName)) {
9197 $wildcards = array_merge($wildcards, $listeners);
9204 $this->sorted[$eventName] = array();
9205 if (isset($this->listeners[$eventName])) {
9206 krsort($this->listeners[$eventName]);
9207 $this->sorted[$eventName] = call_user_func_array(
'array_merge', $this->listeners[$eventName]);
9212 return is_string($listener) ? $this->createClassListener($listener) : $listener;
9217 return function () use($listener,
$container) {
9218 return call_user_func_array($this->createClassCallable($listener,
$container), func_get_args());
9223 list($class, $method) = $this->parseClassCallable($listener);
9224 if ($this->handlerShouldBeQueued($class)) {
9225 return $this->createQueuedHandlerCallable($class, $method);
9227 return array(
$container->make($class), $method);
9232 $segments = explode(
'@', $listener);
9233 return array($segments[0], count($segments) == 2 ? $segments[1] :
'handle');
9238 return (
new ReflectionClass($class))->implementsInterface(
'Illuminate\\Contracts\\Queue\\ShouldBeQueued');
9239 }
catch (Exception $e) {
9245 return function () use($class, $method) {
9246 $arguments = $this->cloneArgumentsForQueueing(func_get_args());
9247 if (method_exists($class,
'queue')) {
9248 $this->callQueueMethodOnHandler($class, $method,
$arguments);
9250 $this->resolveQueue()->push(
'Illuminate\\Events\\CallQueuedHandler@call', array(
'class' => $class,
'method' => $method,
'data' => serialize(
$arguments)));
9256 return array_map(
function (
$a) {
9257 return is_object(
$a) ? clone
$a :
$a;
9262 $handler = (
new ReflectionClass($class))->newInstanceWithoutConstructor();
9263 $handler->queue($this->resolveQueue(),
'Illuminate\\Events\\CallQueuedHandler@call', array(
'class' => $class,
'method' => $method,
'data' => serialize(
$arguments)));
9267 unset($this->listeners[$event], $this->sorted[$event]);
9271 foreach ($this->listeners as $key => $value) {
9272 if (ends_with($key,
'_pushed')) {
9273 $this->forget($key);
9279 return call_user_func($this->queueResolver);
9283 $this->queueResolver = $resolver;
9317 protected $primaryKey =
'id';
9318 protected $perPage = 15;
9319 public $incrementing =
true;
9320 public $timestamps =
true;
9321 protected $attributes = array();
9322 protected $original = array();
9323 protected $relations = array();
9324 protected $hidden = array();
9325 protected $visible = array();
9326 protected $appends = array();
9327 protected $fillable = array();
9328 protected $guarded = array(
'*');
9329 protected $dates = array();
9330 protected $casts = array();
9331 protected $touches = array();
9332 protected $observables = array();
9333 protected $with = array();
9335 public $exists =
false;
9336 public static $snakeAttributes =
true;
9339 protected static $booted = array();
9340 protected static $globalScopes = array();
9341 protected static $unguarded =
false;
9342 protected static $mutatorCache = array();
9343 public static $manyMethods = array(
'belongsToMany',
'morphToMany',
'morphedByMany');
9344 const CREATED_AT =
'created_at';
9345 const UPDATED_AT =
'updated_at';
9348 $this->bootIfNotBooted();
9349 $this->syncOriginal();
9350 $this->fill($attributes);
9354 $class = get_class($this);
9355 if (!isset(static::$booted[$class])) {
9356 static::$booted[$class] =
true;
9357 $this->fireModelEvent(
'booting',
false);
9359 $this->fireModelEvent(
'booted',
false);
9364 static::bootTraits();
9368 foreach (class_uses_recursive(get_called_class()) as $trait) {
9369 if (method_exists(get_called_class(), $method =
'boot' . class_basename($trait))) {
9370 forward_static_call(array(get_called_class(), $method));
9376 static::$globalScopes[get_called_class()][get_class($scope)] = $scope;
9380 return !is_null(static::getGlobalScope($scope));
9384 return array_first(static::$globalScopes[get_called_class()],
function ($key, $value) use($scope) {
9385 return $scope instanceof $value;
9390 return array_get(static::$globalScopes, get_class($this), array());
9394 $instance =
new static();
9395 $className = is_string($class) ? $class : get_class($class);
9396 foreach ($instance->getObservableEvents() as $event) {
9397 if (method_exists($class, $event)) {
9398 static::registerModelEvent($event, $className .
'@' . $event);
9402 public function fill(array $attributes)
9404 $totallyGuarded = $this->totallyGuarded();
9405 foreach ($this->fillableFromArray($attributes) as $key => $value) {
9406 $key = $this->removeTableFromKey($key);
9407 if ($this->isFillable($key)) {
9408 $this->setAttribute($key, $value);
9409 } elseif ($totallyGuarded) {
9418 $this->fill($attributes);
9424 if (count($this->fillable) > 0 && !static::$unguarded) {
9425 return array_intersect_key($attributes, array_flip($this->fillable));
9431 $model =
new static((array) $attributes);
9432 $model->exists = $exists;
9437 $model = $this->newInstance(array(),
true);
9438 $model->setRawAttributes((array) $attributes,
true);
9439 $model->setConnection($connection ?: $this->connection);
9442 public static function hydrate(array $items, $connection = null)
9444 $instance = (
new static())->setConnection($connection);
9446 return $collection->map(
function ($item) use($instance) {
9447 return $instance->newFromBuilder($item);
9450 public static function hydrateRaw($query, $bindings = array(), $connection = null)
9452 $instance = (
new static())->setConnection($connection);
9453 $items = $instance->getConnection()->select($query, $bindings);
9454 return static::hydrate($items, $connection);
9456 public static function create(array $attributes)
9458 $model =
new static($attributes);
9464 if (static::$unguarded) {
9465 return static::create($attributes);
9468 $model = static::create($attributes);
9474 if (!is_null($instance = static::where($attributes)->first())) {
9477 return static::create($attributes);
9481 if (!is_null($instance = static::where($attributes)->first())) {
9484 return new static($attributes);
9488 $instance = static::firstOrNew($attributes);
9489 $instance->fill($values)->save();
9494 return static::where($attributes)->first();
9498 return (
new static())->newQuery();
9500 public static function on($connection = null)
9502 $instance =
new static();
9503 $instance->setConnection($connection);
9504 return $instance->newQuery();
9508 $instance =
new static();
9509 return $instance->newQuery()->useWritePdo();
9511 public static function all($columns = array(
'*'))
9513 $instance =
new static();
9514 return $instance->newQuery()->get($columns);
9516 public static function find($id, $columns = array(
'*'))
9518 return static::query()->find($id, $columns);
9520 public static function findOrNew($id, $columns = array(
'*'))
9522 if (!is_null($model = static::find($id, $columns))) {
9525 return new static();
9527 public function fresh(array $with = array())
9529 $key = $this->getKeyName();
9530 return $this->exists ? static::with($with)->where($key, $this->getKey())->first() : null;
9534 if (is_string($relations)) {
9535 $relations = func_get_args();
9537 $query = $this->newQuery()->with($relations);
9538 $query->eagerLoadRelations(array($this));
9541 public static function with($relations)
9543 if (is_string($relations)) {
9544 $relations = func_get_args();
9546 $instance =
new static();
9547 return $instance->newQuery()->with($relations);
9549 public function hasOne($related, $foreignKey = null, $localKey = null)
9551 $foreignKey = $foreignKey ?: $this->getForeignKey();
9552 $instance =
new $related();
9553 $localKey = $localKey ?: $this->getKeyName();
9554 return new HasOne($instance->newQuery(), $this, $instance->getTable() .
'.' . $foreignKey, $localKey);
9556 public function morphOne($related, $name, $type = null, $id = null, $localKey = null)
9558 $instance =
new $related();
9559 list($type, $id) = $this->getMorphs($name, $type, $id);
9560 $table = $instance->getTable();
9561 $localKey = $localKey ?: $this->getKeyName();
9562 return new MorphOne($instance->newQuery(), $this, $table .
'.' . $type, $table .
'.' . $id, $localKey);
9564 public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null)
9566 if (is_null($relation)) {
9567 list(, $caller) = debug_backtrace(
false, 2);
9568 $relation = $caller[
'function'];
9570 if (is_null($foreignKey)) {
9571 $foreignKey = snake_case($relation) .
'_id';
9573 $instance =
new $related();
9574 $query = $instance->newQuery();
9575 $otherKey = $otherKey ?: $instance->getKeyName();
9576 return new BelongsTo($query, $this, $foreignKey, $otherKey, $relation);
9578 public function morphTo($name = null, $type = null, $id = null)
9580 if (is_null($name)) {
9581 list(, $caller) = debug_backtrace(
false, 2);
9582 $name = snake_case($caller[
'function']);
9584 list($type, $id) = $this->getMorphs($name, $type, $id);
9585 if (is_null($class = $this->{$type})) {
9586 return new MorphTo($this->newQuery(), $this, $id, null, $type, $name);
9588 $instance =
new $class();
9589 return new MorphTo($instance->newQuery(), $this, $id, $instance->getKeyName(), $type, $name);
9592 public function hasMany($related, $foreignKey = null, $localKey = null)
9594 $foreignKey = $foreignKey ?: $this->getForeignKey();
9595 $instance =
new $related();
9596 $localKey = $localKey ?: $this->getKeyName();
9597 return new HasMany($instance->newQuery(), $this, $instance->getTable() .
'.' . $foreignKey, $localKey);
9599 public function hasManyThrough($related, $through, $firstKey = null, $secondKey = null)
9601 $through =
new $through();
9602 $firstKey = $firstKey ?: $this->getForeignKey();
9603 $secondKey = $secondKey ?: $through->getForeignKey();
9604 return new HasManyThrough((
new $related())->newQuery(), $this, $through, $firstKey, $secondKey);
9606 public function morphMany($related, $name, $type = null, $id = null, $localKey = null)
9608 $instance =
new $related();
9609 list($type, $id) = $this->getMorphs($name, $type, $id);
9610 $table = $instance->getTable();
9611 $localKey = $localKey ?: $this->getKeyName();
9612 return new MorphMany($instance->newQuery(), $this, $table .
'.' . $type, $table .
'.' . $id, $localKey);
9614 public function belongsToMany($related, $table = null, $foreignKey = null, $otherKey = null, $relation = null)
9616 if (is_null($relation)) {
9617 $relation = $this->getBelongsToManyCaller();
9619 $foreignKey = $foreignKey ?: $this->getForeignKey();
9620 $instance =
new $related();
9621 $otherKey = $otherKey ?: $instance->getForeignKey();
9622 if (is_null($table)) {
9623 $table = $this->joiningTable($related);
9625 $query = $instance->newQuery();
9626 return new BelongsToMany($query, $this, $table, $foreignKey, $otherKey, $relation);
9628 public function morphToMany($related, $name, $table = null, $foreignKey = null, $otherKey = null, $inverse =
false)
9630 $caller = $this->getBelongsToManyCaller();
9631 $foreignKey = $foreignKey ?: $name .
'_id';
9632 $instance =
new $related();
9633 $otherKey = $otherKey ?: $instance->getForeignKey();
9634 $query = $instance->newQuery();
9635 $table = $table ?: str_plural($name);
9636 return new MorphToMany($query, $this, $name, $table, $foreignKey, $otherKey, $caller, $inverse);
9638 public function morphedByMany($related, $name, $table = null, $foreignKey = null, $otherKey = null)
9640 $foreignKey = $foreignKey ?: $this->getForeignKey();
9641 $otherKey = $otherKey ?: $name .
'_id';
9642 return $this->morphToMany($related, $name, $table, $foreignKey, $otherKey,
true);
9646 $self = __FUNCTION__;
9647 $caller = array_first(debug_backtrace(
false),
function ($key, $trace) use($self) {
9648 $caller = $trace[
'function'];
9649 return !in_array($caller, Model::$manyMethods) && $caller != $self;
9651 return !is_null($caller) ? $caller[
'function'] : null;
9655 $base = snake_case(class_basename($this));
9656 $related = snake_case(class_basename($related));
9657 $models = array($related, $base);
9659 return strtolower(implode(
'_', $models));
9664 $ids = is_array($ids) ? $ids : func_get_args();
9665 $instance =
new static();
9666 $key = $instance->getKeyName();
9667 foreach ($instance->whereIn($key, $ids)->get() as $model) {
9668 if ($model->delete()) {
9674 public function delete()
9676 if (is_null($this->primaryKey)) {
9677 throw new Exception(
'No primary key defined on model.');
9679 if ($this->exists) {
9680 if ($this->fireModelEvent(
'deleting') ===
false) {
9683 $this->touchOwners();
9685 $this->exists =
false;
9686 $this->fireModelEvent(
'deleted',
false);
9692 return $this->
delete();
9696 $this->setKeysForSaveQuery($this->newQuery())->delete();
9698 public static function saving($callback, $priority = 0)
9700 static::registerModelEvent(
'saving', $callback, $priority);
9702 public static function saved($callback, $priority = 0)
9704 static::registerModelEvent(
'saved', $callback, $priority);
9706 public static function updating($callback, $priority = 0)
9708 static::registerModelEvent(
'updating', $callback, $priority);
9710 public static function updated($callback, $priority = 0)
9712 static::registerModelEvent(
'updated', $callback, $priority);
9714 public static function creating($callback, $priority = 0)
9716 static::registerModelEvent(
'creating', $callback, $priority);
9718 public static function created($callback, $priority = 0)
9720 static::registerModelEvent(
'created', $callback, $priority);
9722 public static function deleting($callback, $priority = 0)
9724 static::registerModelEvent(
'deleting', $callback, $priority);
9726 public static function deleted($callback, $priority = 0)
9728 static::registerModelEvent(
'deleted', $callback, $priority);
9732 if (!isset(static::$dispatcher)) {
9735 $instance =
new static();
9736 foreach ($instance->getObservableEvents() as $event) {
9737 static::$dispatcher->forget(
"eloquent.{$event}: " . get_called_class());
9742 if (isset(static::$dispatcher)) {
9743 $name = get_called_class();
9744 static::$dispatcher->listen(
"eloquent.{$event}: {$name}", $callback, $priority);
9749 return array_merge(array(
'creating',
'created',
'updating',
'updated',
'deleting',
'deleted',
'saving',
'saved',
'restoring',
'restored'), $this->observables);
9753 $this->observables = $observables;
9757 $observables = is_array($observables) ? $observables : func_get_args();
9758 $this->observables = array_unique(array_merge($this->observables, $observables));
9762 $observables = is_array($observables) ? $observables : func_get_args();
9763 $this->observables = array_diff($this->observables, $observables);
9767 return $this->incrementOrDecrement($column, $amount,
'increment');
9771 return $this->incrementOrDecrement($column, $amount,
'decrement');
9775 $query = $this->newQuery();
9776 if (!$this->exists) {
9777 return $query->{$method}($column, $amount);
9779 $this->incrementOrDecrementAttributeValue($column, $amount, $method);
9780 return $query->where($this->getKeyName(), $this->getKey())->{$method}($column, $amount);
9784 $this->{$column} = $this->{$column} + ($method ==
'increment' ? $amount : $amount * -1);
9785 $this->syncOriginalAttribute($column);
9787 public function update(array $attributes = array())
9789 if (!$this->exists) {
9790 return $this->newQuery()->update($attributes);
9792 return $this->fill($attributes)->save();
9796 if (!$this->save()) {
9799 foreach ($this->relations as $models) {
9800 $models = $models instanceof
Collection ? $models->
all() : array($models);
9801 foreach (array_filter($models) as $model) {
9802 if (!$model->push()) {
9809 public function save(array $options = array())
9811 $query = $this->newQueryWithoutScopes();
9812 if ($this->fireModelEvent(
'saving') ===
false) {
9815 if ($this->exists) {
9816 $saved = $this->performUpdate($query, $options);
9818 $saved = $this->performInsert($query, $options);
9821 $this->finishSave($options);
9827 $this->fireModelEvent(
'saved',
false);
9828 $this->syncOriginal();
9829 if (array_get($options,
'touch',
true)) {
9830 $this->touchOwners();
9835 $dirty = $this->getDirty();
9836 if (count($dirty) > 0) {
9837 if ($this->fireModelEvent(
'updating') ===
false) {
9840 if ($this->timestamps && array_get($options,
'timestamps',
true)) {
9841 $this->updateTimestamps();
9843 $dirty = $this->getDirty();
9844 if (count($dirty) > 0) {
9845 $this->setKeysForSaveQuery($query)->update($dirty);
9846 $this->fireModelEvent(
'updated',
false);
9853 if ($this->fireModelEvent(
'creating') ===
false) {
9856 if ($this->timestamps && array_get($options,
'timestamps',
true)) {
9857 $this->updateTimestamps();
9859 $attributes = $this->attributes;
9860 if ($this->incrementing) {
9861 $this->insertAndSetId($query, $attributes);
9863 $query->insert($attributes);
9865 $this->exists =
true;
9866 $this->fireModelEvent(
'created',
false);
9871 $id = $query->insertGetId($attributes, $keyName = $this->getKeyName());
9872 $this->setAttribute($keyName, $id);
9876 foreach ($this->
touches as $relation) {
9877 $this->{$relation}()->
touch();
9878 if (!is_null($this->{$relation})) {
9879 $this->{$relation}->touchOwners();
9885 return in_array($relation, $this->
touches);
9889 if (!isset(static::$dispatcher)) {
9892 $event =
"eloquent.{$event}: " . get_class($this);
9893 $method = $halt ?
'until' :
'fire';
9894 return static::$dispatcher->{$method}($event, $this);
9898 $query->
where($this->getKeyName(),
'=', $this->getKeyForSaveQuery());
9903 if (isset($this->original[$this->getKeyName()])) {
9904 return $this->original[$this->getKeyName()];
9906 return $this->getAttribute($this->getKeyName());
9910 if (!$this->timestamps) {
9913 $this->updateTimestamps();
9914 return $this->save();
9918 $time = $this->freshTimestamp();
9919 if (!$this->isDirty(static::UPDATED_AT)) {
9920 $this->setUpdatedAt($time);
9922 if (!$this->exists && !$this->isDirty(static::CREATED_AT)) {
9923 $this->setCreatedAt($time);
9928 $this->{static::CREATED_AT} = $value;
9932 $this->{static::UPDATED_AT} = $value;
9936 return static::CREATED_AT;
9940 return static::UPDATED_AT;
9948 return $this->fromDateTime($this->freshTimestamp());
9952 $builder = $this->newQueryWithoutScopes();
9953 return $this->applyGlobalScopes($builder);
9957 $this->getGlobalScope($scope)->remove($builder = $this->newQuery(), $this);
9962 $builder = $this->newEloquentBuilder($this->newBaseQueryBuilder());
9963 return $builder->setModel($this)->with($this->with);
9967 foreach ($this->getGlobalScopes() as $scope) {
9968 $scope->apply($builder, $this);
9974 foreach ($this->getGlobalScopes() as $scope) {
9975 $scope->remove($builder, $this);
9985 $conn = $this->getConnection();
9986 $grammar = $conn->getQueryGrammar();
9987 return new QueryBuilder($conn, $grammar, $conn->getPostProcessor());
9995 return new Pivot($parent, $attributes, $table, $exists);
9999 if (isset($this->table)) {
10000 return $this->table;
10002 return str_replace(
'\\',
'', snake_case(str_plural(class_basename($this))));
10006 $this->table = $table;
10010 return $this->getAttribute($this->getKeyName());
10014 return $this->getKey();
10018 return $this->primaryKey;
10022 $this->primaryKey = $key;
10026 return $this->getTable() .
'.' . $this->getKeyName();
10030 return $this->getAttribute($this->getRouteKeyName());
10034 return $this->getKeyName();
10038 return $this->timestamps;
10042 $type = $type ?: $name .
'_type';
10043 $id = $id ?: $name .
'_id';
10044 return array($type, $id);
10048 return $this->morphClass ?: get_class($this);
10052 return $this->perPage;
10056 $this->perPage = $perPage;
10060 return snake_case(class_basename($this)) .
'_id';
10064 return $this->hidden;
10068 $this->hidden = $hidden;
10072 $attributes = is_array($attributes) ? $attributes : func_get_args();
10073 $this->hidden = array_merge($this->hidden, $attributes);
10077 return $this->visible;
10081 $this->visible = $visible;
10085 $attributes = is_array($attributes) ? $attributes : func_get_args();
10086 $this->visible = array_merge($this->visible, $attributes);
10090 $this->appends = $appends;
10094 return $this->fillable;
10098 $this->fillable = $fillable;
10103 return $this->guarded;
10107 $this->guarded = $guarded;
10112 static::$unguarded = $state;
10116 static::$unguarded =
false;
10120 return static::$unguarded;
10124 if (static::$unguarded) {
10125 return $callback();
10128 $result = $callback();
10134 if (static::$unguarded) {
10137 if (in_array($key, $this->fillable)) {
10140 if ($this->isGuarded($key)) {
10143 return empty($this->fillable) && !starts_with($key,
'_');
10147 return in_array($key, $this->guarded) || $this->guarded == array(
'*');
10151 return count($this->fillable) == 0 && $this->guarded == array(
'*');
10155 if (!str_contains($key,
'.')) {
10158 return last(explode(
'.', $key));
10162 return $this->touches;
10170 return $this->incrementing;
10174 $this->incrementing = $value;
10178 return json_encode($this->toArray(), $options);
10182 return $this->toArray();
10186 $attributes = $this->attributesToArray();
10187 return array_merge($attributes, $this->relationsToArray());
10191 $attributes = $this->getArrayableAttributes();
10192 foreach ($this->getDates() as $key) {
10193 if (!isset($attributes[$key])) {
10196 $attributes[$key] = (string) $this->asDateTime($attributes[$key]);
10198 $mutatedAttributes = $this->getMutatedAttributes();
10199 foreach ($mutatedAttributes as $key) {
10200 if (!array_key_exists($key, $attributes)) {
10203 $attributes[$key] = $this->mutateAttributeForArray($key, $attributes[$key]);
10205 foreach ($this->casts as $key => $value) {
10206 if (!array_key_exists($key, $attributes) || in_array($key, $mutatedAttributes)) {
10209 $attributes[$key] = $this->castAttribute($key, $attributes[$key]);
10211 foreach ($this->getArrayableAppends() as $key) {
10212 $attributes[$key] = $this->mutateAttributeForArray($key, null);
10214 return $attributes;
10218 return $this->getArrayableItems($this->attributes);
10222 if (!count($this->appends)) {
10225 return $this->getArrayableItems(array_combine($this->appends, $this->appends));
10229 $attributes = array();
10230 foreach ($this->getArrayableRelations() as $key => $value) {
10231 if (in_array($key, $this->hidden)) {
10235 $relation = $value->toArray();
10236 } elseif (is_null($value)) {
10237 $relation = $value;
10239 if (static::$snakeAttributes) {
10240 $key = snake_case($key);
10242 if (isset($relation) || is_null($value)) {
10243 $attributes[$key] = $relation;
10247 return $attributes;
10251 return $this->getArrayableItems($this->relations);
10255 if (count($this->visible) > 0) {
10256 return array_intersect_key($values, array_flip($this->visible));
10258 return array_diff_key($values, array_flip($this->hidden));
10262 $inAttributes = array_key_exists($key, $this->attributes);
10263 if ($inAttributes || $this->hasGetMutator($key)) {
10264 return $this->getAttributeValue($key);
10266 if (array_key_exists($key, $this->relations)) {
10267 return $this->relations[$key];
10269 if (method_exists($this, $key)) {
10270 return $this->getRelationshipFromMethod($key);
10275 $value = $this->getAttributeFromArray($key);
10276 if ($this->hasGetMutator($key)) {
10277 return $this->mutateAttribute($key, $value);
10279 if ($this->hasCast($key)) {
10280 $value = $this->castAttribute($key, $value);
10281 } elseif (in_array($key, $this->getDates())) {
10282 if (!is_null($value)) {
10283 return $this->asDateTime($value);
10290 if (array_key_exists($key, $this->attributes)) {
10291 return $this->attributes[$key];
10296 $relations = $this->{$method}();
10297 if (!$relations instanceof
Relation) {
10298 throw new LogicException(
'Relationship method must return an object of type ' .
'Illuminate\\Database\\Eloquent\\Relations\\Relation');
10300 return $this->relations[$method] = $relations->getResults();
10304 return method_exists($this,
'get' . studly_case($key) .
'Attribute');
10308 return $this->{
'get' . studly_case($key) .
'Attribute'}($value);
10312 $value = $this->mutateAttribute($key, $value);
10317 return array_key_exists($key, $this->casts);
10321 if ($this->hasCast($key)) {
10322 return in_array($this->getCastType($key), array(
'array',
'json',
'object',
'collection'),
true);
10328 return trim(strtolower($this->casts[$key]));
10332 if (is_null($value)) {
10335 switch ($this->getCastType($key)) {
10338 return (
int) $value;
10342 return (
double) $value;
10344 return (
string) $value;
10347 return (
bool) $value;
10349 return json_decode($value);
10352 return json_decode($value,
true);
10354 return $this->newCollection(json_decode($value,
true));
10361 if ($this->hasSetMutator($key)) {
10362 $method =
'set' . studly_case($key) .
'Attribute';
10363 return $this->{$method}($value);
10364 } elseif (in_array($key, $this->getDates()) && $value) {
10365 $value = $this->fromDateTime($value);
10367 if ($this->isJsonCastable($key)) {
10368 $value = json_encode($value);
10370 $this->attributes[$key] = $value;
10374 return method_exists($this,
'set' . studly_case($key) .
'Attribute');
10378 $defaults = array(static::CREATED_AT, static::UPDATED_AT);
10379 return array_merge($this->dates, $defaults);
10383 $format = $this->getDateFormat();
10384 if ($value instanceof DateTime) {
10385 } elseif (is_numeric($value)) {
10386 $value = Carbon::createFromTimestamp($value);
10387 } elseif (preg_match(
'/^(\\d{4})-(\\d{2})-(\\d{2})$/', $value)) {
10388 $value = Carbon::createFromFormat(
'Y-m-d', $value)->startOfDay();
10390 $value = Carbon::createFromFormat($format, $value);
10392 return $value->format($format);
10396 if (is_numeric($value)) {
10397 return Carbon::createFromTimestamp($value);
10398 } elseif (preg_match(
'/^(\\d{4})-(\\d{2})-(\\d{2})$/', $value)) {
10399 return Carbon::createFromFormat(
'Y-m-d', $value)->startOfDay();
10400 } elseif (!$value instanceof DateTime) {
10401 $format = $this->getDateFormat();
10402 return Carbon::createFromFormat($format, $value);
10404 return Carbon::instance($value);
10408 return $this->getConnection()->getQueryGrammar()->getDateFormat();
10412 $except = $except ?: array($this->getKeyName(), $this->getCreatedAtColumn(), $this->getUpdatedAtColumn());
10413 $attributes = array_except($this->attributes, $except);
10414 with($instance =
new static())->setRawAttributes($attributes);
10415 return $instance->setRelations($this->relations);
10419 return $this->attributes;
10423 $this->attributes = $attributes;
10425 $this->syncOriginal();
10430 return array_get($this->original, $key, $default);
10434 $this->original = $this->attributes;
10439 $this->original[$attribute] = $this->attributes[$attribute];
10444 $dirty = $this->getDirty();
10445 if (is_null($attributes)) {
10446 return count($dirty) > 0;
10448 if (!is_array($attributes)) {
10449 $attributes = func_get_args();
10451 foreach ($attributes as $attribute) {
10452 if (array_key_exists($attribute, $dirty)) {
10461 foreach ($this->attributes as $key => $value) {
10462 if (!array_key_exists($key, $this->original)) {
10463 $dirty[$key] = $value;
10464 } elseif ($value !== $this->original[$key] && !$this->originalIsNumericallyEquivalent($key)) {
10465 $dirty[$key] = $value;
10472 $current = $this->attributes[$key];
10473 $original = $this->original[$key];
10474 return is_numeric($current) && is_numeric($original) && strcmp((
string) $current, (
string) $original) === 0;
10478 return $this->relations;
10482 return $this->relations[$relation];
10486 $this->relations[$relation] = $value;
10491 $this->relations = $relations;
10496 return static::resolveConnection($this->connection);
10500 return $this->connection;
10504 $this->connection = $name;
10509 return static::$resolver->connection($connection);
10513 return static::$resolver;
10517 static::$resolver = $resolver;
10521 static::$resolver = null;
10525 return static::$dispatcher;
10529 static::$dispatcher = $dispatcher;
10533 static::$dispatcher = null;
10537 $class = get_class($this);
10538 if (!isset(static::$mutatorCache[$class])) {
10539 static::cacheMutatedAttributes($class);
10541 return static::$mutatorCache[$class];
10545 $mutatedAttributes = array();
10546 foreach (get_class_methods($class) as $method) {
10547 if (strpos($method,
'Attribute') !==
false && preg_match(
'/^get(.+)Attribute$/', $method, $matches)) {
10548 if (static::$snakeAttributes) {
10549 $matches[1] = snake_case($matches[1]);
10551 $mutatedAttributes[] = lcfirst($matches[1]);
10554 static::$mutatorCache[$class] = $mutatedAttributes;
10558 return $this->getAttribute($key);
10562 $this->setAttribute($key, $value);
10566 return isset($this->{$offset});
10570 return $this->{$offset};
10574 $this->{$offset} = $value;
10578 unset($this->{$offset});
10582 return isset($this->attributes[$key]) || isset($this->relations[$key]) || $this->hasGetMutator($key) && !is_null($this->getAttributeValue($key));
10586 unset($this->attributes[$key], $this->relations[$key]);
10590 if (in_array($method, array(
'increment',
'decrement'))) {
10591 return call_user_func_array(array($this, $method), $parameters);
10593 $query = $this->newQuery();
10594 return call_user_func_array(array($query, $method), $parameters);
10598 $instance =
new static();
10599 return call_user_func_array(array($instance, $method), $parameters);
10603 return $this->toJson();
10607 $this->bootIfNotBooted();
10613 use InvalidArgumentException;
10619 protected $connections = array();
10620 protected $extensions = array();
10628 list($name, $type) = $this->parseConnectionName($name);
10629 if (!isset($this->connections[$name])) {
10630 $connection = $this->makeConnection($name);
10631 $this->setPdoForType($connection, $type);
10632 $this->connections[$name] = $this->
prepare($connection);
10634 return $this->connections[$name];
10638 $name = $name ?: $this->getDefaultConnection();
10639 return Str::endsWith($name, array(
'::read',
'::write')) ? explode(
'::', $name, 2) : array($name, null);
10643 $this->disconnect($name);
10644 unset($this->connections[$name]);
10648 if (isset($this->connections[$name = $name ?: $this->getDefaultConnection()])) {
10649 $this->connections[$name]->disconnect();
10654 $this->disconnect($name = $name ?: $this->getDefaultConnection());
10655 if (!isset($this->connections[$name])) {
10656 return $this->connection($name);
10658 return $this->refreshPdoConnections($name);
10662 $fresh = $this->makeConnection($name);
10663 return $this->connections[$name]->setPdo($fresh->getPdo())->setReadPdo($fresh->getReadPdo());
10667 $config = $this->getConfig($name);
10668 if (isset($this->extensions[$name])) {
10669 return call_user_func($this->extensions[$name], $config, $name);
10671 $driver = $config[
'driver'];
10672 if (isset($this->extensions[$driver])) {
10673 return call_user_func($this->extensions[$driver], $config, $name);
10675 return $this->
factory->make($config, $name);
10679 $connection->
setFetchMode($this->app[
'config'][
'database.fetch']);
10680 if ($this->app->bound(
'events')) {
10684 $this->reconnect($connection->
getName());
10686 return $connection;
10690 if ($type ==
'read') {
10692 } elseif ($type ==
'write') {
10695 return $connection;
10699 $name = $name ?: $this->getDefaultConnection();
10700 $connections = $this->app[
'config'][
'database.connections'];
10701 if (is_null($config = array_get($connections, $name))) {
10702 throw new InvalidArgumentException(
"Database [{$name}] not configured.");
10708 return $this->app[
'config'][
'database.default'];
10712 $this->app[
'config'][
'database.default'] = $name;
10714 public function extend($name, callable $resolver)
10716 $this->extensions[$name] = $resolver;
10720 return $this->connections;
10724 return call_user_func_array(array($this->connection(), $method), $parameters);
10731 public function connection($name = null);
10732 public function getDefaultConnection();
10733 public function setDefaultConnection($name);
10738 use InvalidArgumentException;
10751 public function make(array $config, $name = null)
10753 $config = $this->parseConfig($config, $name);
10754 if (isset($config[
'read'])) {
10755 return $this->createReadWriteConnection($config);
10757 return $this->createSingleConnection($config);
10761 $pdo = $this->createConnector($config)->connect($config);
10762 return $this->createConnection($config[
'driver'], $pdo, $config[
'database'], $config[
'prefix'], $config);
10766 $connection = $this->createSingleConnection($this->getWriteConfig($config));
10767 return $connection->setReadPdo($this->createReadPdo($config));
10771 $readConfig = $this->getReadConfig($config);
10772 return $this->createConnector($readConfig)->connect($readConfig);
10776 $readConfig = $this->getReadWriteConfig($config,
'read');
10777 return $this->mergeReadWriteConfig($config, $readConfig);
10781 $writeConfig = $this->getReadWriteConfig($config,
'write');
10782 return $this->mergeReadWriteConfig($config, $writeConfig);
10786 if (isset($config[$type][0])) {
10787 return $config[$type][array_rand($config[$type])];
10789 return $config[$type];
10793 return array_except(array_merge($config, $merge), array(
'read',
'write'));
10797 return array_add(array_add($config,
'prefix',
''),
'name', $name);
10801 if (!isset($config[
'driver'])) {
10802 throw new InvalidArgumentException(
'A driver must be specified.');
10804 if ($this->container->bound($key =
"db.connector.{$config['driver']}")) {
10805 return $this->container->make($key);
10807 switch ($config[
'driver']) {
10817 throw new InvalidArgumentException(
"Unsupported driver [{$config['driver']}]");
10819 protected function createConnection($driver, PDO $connection, $database, $prefix =
'', array $config = array())
10821 if ($this->container->bound($key =
"db.connection.{$driver}")) {
10822 return $this->container->make($key, array($connection, $database, $prefix, $config));
10826 return new MySqlConnection($connection, $database, $prefix, $config);
10834 throw new InvalidArgumentException(
"Unsupported driver [{$driver}]");
10843 public function getHandler();
10844 public function handlerNeedsRequest();
10845 public function setRequestOnHandler(
Request $request);
10861 protected $sessionHandled =
false;
10864 $this->manager = $manager;
10868 $this->sessionHandled =
true;
10869 if ($this->sessionConfigured()) {
10871 $request->setSession($session);
10874 if ($this->sessionConfigured()) {
10875 $this->storeCurrentUrl($request, $session);
10876 $this->collectGarbage($session);
10877 $this->addCookieToResponse(
$response, $session);
10883 if ($this->sessionHandled && $this->sessionConfigured() && !$this->usingCookieSessions()) {
10884 $this->manager->driver()->save();
10889 with($session = $this->getSession($request))->setRequestOnHandler($request);
10895 $session = $this->manager->driver();
10896 $session->setId($request->cookies->
get($session->getName()));
10901 if ($request->
method() ===
'GET' && $request->
route() && !$request->
ajax()) {
10902 $session->setPreviousUrl($request->
fullUrl());
10907 $config = $this->manager->getSessionConfig();
10908 if ($this->configHitsLottery($config)) {
10909 $session->
getHandler()->gc($this->getSessionLifetimeInSeconds());
10914 return mt_rand(1, $config[
'lottery'][1]) <= $config[
'lottery'][0];
10918 if ($this->usingCookieSessions()) {
10919 $this->manager->driver()->save();
10921 if ($this->sessionIsPersistent($config = $this->manager->getSessionConfig())) {
10922 $response->headers->setCookie(
new Cookie($session->
getName(), $session->
getId(), $this->getCookieExpirationDate(), $config[
'path'], $config[
'domain'], array_get($config,
'secure',
false)));
10927 return array_get($this->manager->getSessionConfig(),
'lifetime') * 60;
10931 $config = $this->manager->getSessionConfig();
10932 return $config[
'expire_on_close'] ? 0 :
Carbon::now()->addMinutes($config[
'lifetime']);
10936 return !is_null(array_get($this->manager->getSessionConfig(),
'driver'));
10940 $config = $config ?: $this->manager->getSessionConfig();
10941 return !in_array($config[
'driver'], array(null,
'array'));
10945 if (!$this->sessionConfigured()) {
10954 use InvalidArgumentException;
10962 protected $attributes = array();
10963 protected $bags = array();
10965 protected $bagData = array();
10967 protected $started =
false;
10968 public function __construct($name, SessionHandlerInterface $handler, $id = null)
10971 $this->
name = $name;
10972 $this->handler = $handler;
10977 $this->loadSession();
10978 if (!$this->has(
'_token')) {
10979 $this->regenerateToken();
10981 return $this->started =
true;
10985 $this->attributes = array_merge($this->attributes, $this->readFromHandler());
10986 foreach (array_merge($this->bags, array($this->metaBag)) as $bag) {
10987 $this->initializeLocalBag($bag);
10988 $bag->initialize($this->bagData[$bag->getStorageKey()]);
10993 $data = $this->handler->read($this->getId());
10995 $data = @unserialize($this->prepareForUnserialize($data));
10996 if ($data !==
false) {
11008 $this->bagData[$bag->getStorageKey()] = $this->pull($bag->getStorageKey(), array());
11016 if (!$this->isValidId($id)) {
11017 $id = $this->generateSessionId();
11023 return is_string($id) && preg_match(
'/^[a-f0-9]{40}$/', $id);
11027 return sha1(uniqid(
'',
true) . str_random(25) . microtime(
true));
11031 return $this->name;
11035 $this->
name = $name;
11039 $this->attributes = array();
11040 return $this->migrate();
11042 public function migrate($destroy =
false, $lifetime = null)
11045 $this->handler->destroy($this->getId());
11047 $this->setExists(
false);
11048 $this->
id = $this->generateSessionId();
11053 return $this->migrate($destroy);
11057 $this->addBagDataToSession();
11058 $this->ageFlashData();
11059 $this->handler->write($this->getId(), $this->prepareForStorage(serialize($this->attributes)));
11060 $this->started =
false;
11068 foreach (array_merge($this->bags, array($this->metaBag)) as $bag) {
11069 $this->put($bag->getStorageKey(), $this->bagData[$bag->getStorageKey()]);
11074 foreach ($this->
get(
'flash.old', array()) as $old) {
11075 $this->forget($old);
11077 $this->put(
'flash.old', $this->
get(
'flash.new', array()));
11078 $this->put(
'flash.new', array());
11082 return !is_null($this->
get($name));
11084 public function get($name, $default = null)
11086 return array_get($this->attributes, $name, $default);
11088 public function pull($key, $default = null)
11090 return array_pull($this->attributes, $key, $default);
11094 $old = $this->getOldInput($key);
11095 return is_null($key) ? count($old) > 0 : !is_null($old);
11099 $input = $this->
get(
'_old_input', array());
11100 return array_get($input, $key, $default);
11102 public function set($name, $value)
11104 array_set($this->attributes, $name, $value);
11106 public function put($key, $value = null)
11108 if (!is_array($key)) {
11109 $key = array($key => $value);
11111 foreach ($key as $arrayKey => $arrayValue) {
11112 $this->
set($arrayKey, $arrayValue);
11117 $array = $this->
get($key, array());
11119 $this->put($key, $array);
11123 $this->put($key, $value);
11124 $this->push(
'flash.new', $key);
11125 $this->removeFromOldFlashData(array($key));
11129 $this->flash(
'_old_input', $value);
11133 $this->mergeNewFlashes($this->
get(
'flash.old', array()));
11134 $this->put(
'flash.old', array());
11138 $keys = is_array($keys) ? $keys : func_get_args();
11139 $this->mergeNewFlashes($keys);
11140 $this->removeFromOldFlashData($keys);
11144 $values = array_unique(array_merge($this->
get(
'flash.new', array()), $keys));
11145 $this->put(
'flash.new', $values);
11149 $this->put(
'flash.old', array_diff($this->
get(
'flash.old', array()), $keys));
11153 return $this->attributes;
11157 $this->put($attributes);
11159 public function remove($name)
11161 return array_pull($this->attributes, $name);
11165 array_forget($this->attributes, $key);
11169 $this->attributes = array();
11170 foreach ($this->bags as $bag) {
11180 return $this->started;
11188 return array_get($this->bags, $name,
function () {
11189 throw new InvalidArgumentException(
'Bag not registered.');
11194 return $this->metaBag;
11198 return array_get($this->bagData, $name, array());
11202 return $this->
get(
'_token');
11206 return $this->token();
11210 $this->put(
'_token', str_random(40));
11214 return $this->
get(
'_previous.url');
11218 return $this->put(
'_previous.url', $url);
11223 $this->handler->setExists($value);
11228 return $this->handler;
11236 if ($this->handlerNeedsRequest()) {
11237 $this->handler->setRequest($request);
11249 return $this->buildSession(parent::callCustomCreator($driver));
11257 $lifetime = $this->app[
'config'][
'session.lifetime'];
11262 return $this->createNativeDriver();
11266 $path = $this->app[
'config'][
'session.files'];
11271 $connection = $this->getDatabaseConnection();
11272 $table = $this->app[
'config'][
'session.table'];
11277 $connection = $this->app[
'config'][
'session.connection'];
11278 return $this->app[
'db']->connection($connection);
11282 return $this->createCacheBased(
'apc');
11286 return $this->createCacheBased(
'memcached');
11290 return $this->createCacheBased(
'wincache');
11294 $handler = $this->createCacheHandler(
'redis');
11295 $handler->getCache()->getStore()->setConnection($this->app[
'config'][
'session.connection']);
11296 return $this->buildSession($handler);
11300 return $this->buildSession($this->createCacheHandler($driver));
11304 $minutes = $this->app[
'config'][
'session.lifetime'];
11309 if ($this->app[
'config'][
'session.encrypt']) {
11310 return new EncryptedStore($this->app[
'config'][
'session.cookie'], $handler, $this->app[
'encrypter']);
11312 return new Store($this->app[
'config'][
'session.cookie'], $handler);
11317 return $this->app[
'config'][
'session'];
11321 return $this->app[
'config'][
'session.driver'];
11325 $this->app[
'config'][
'session.driver'] = $name;
11331 use InvalidArgumentException;
11335 protected $customCreators = array();
11336 protected $drivers = array();
11341 public abstract function getDefaultDriver();
11344 $driver = $driver ?: $this->getDefaultDriver();
11345 if (!isset($this->drivers[$driver])) {
11346 $this->drivers[$driver] = $this->createDriver($driver);
11348 return $this->drivers[$driver];
11352 $method =
'create' . ucfirst($driver) .
'Driver';
11353 if (isset($this->customCreators[$driver])) {
11354 return $this->callCustomCreator($driver);
11355 } elseif (method_exists($this, $method)) {
11356 return $this->{$method}();
11358 throw new InvalidArgumentException(
"Driver [{$driver}] not supported.");
11362 return $this->customCreators[$driver](
$this->app);
11364 public function extend($driver, Closure $callback)
11366 $this->customCreators[$driver] = $callback;
11371 return $this->drivers;
11375 return call_user_func_array(array($this->driver(), $method), $parameters);
11385 use JsonSerializable;
11386 use IteratorAggregate;
11391 protected $items = array();
11394 $items = is_null($items) ? array() : $this->getArrayableItems($items);
11395 $this->items = (array) $items;
11397 public static function make($items = null)
11399 return new static($items);
11403 return $this->items;
11407 $results = array();
11408 foreach ($this->items as $values) {
11410 $values = $values->all();
11412 $results = array_merge($results, $values);
11414 return new static($results);
11418 if (func_num_args() == 2) {
11419 return $this->
contains(
function ($k, $item) use($key, $value) {
11420 return data_get($item, $key) == $value;
11423 if ($this->useAsCallable($key)) {
11424 return !is_null($this->first($key));
11426 return in_array($key, $this->items);
11430 return new static(array_diff($this->items, $this->getArrayableItems($items)));
11432 public function each(callable $callback)
11434 array_map($callback, $this->items);
11439 return new static(array_fetch($this->items, $key));
11443 return new static(array_filter($this->items, $callback));
11445 public function where($key, $value, $strict =
true)
11447 return $this->
filter(
function ($item) use($key, $value, $strict) {
11448 return $strict ? data_get($item, $key) === $value : data_get($item, $key) == $value;
11453 return $this->where($key, $value,
false);
11455 public function first(callable $callback = null, $default = null)
11457 if (is_null($callback)) {
11458 return count($this->items) > 0 ? reset($this->items) : null;
11460 return array_first($this->items, $callback, $default);
11464 return new static(array_flatten($this->items));
11468 return new static(array_flip($this->items));
11472 $this->offsetUnset($key);
11474 public function get($key, $default = null)
11476 if ($this->offsetExists($key)) {
11477 return $this->items[$key];
11479 return value($default);
11483 if (!$this->useAsCallable($groupBy)) {
11484 return $this->groupBy($this->valueRetriever($groupBy));
11486 $results = array();
11487 foreach ($this->items as $key => $value) {
11488 $results[$groupBy($value, $key)][] = $value;
11490 return new static($results);
11494 if (!$this->useAsCallable($keyBy)) {
11495 return $this->keyBy($this->valueRetriever($keyBy));
11497 $results = array();
11498 foreach ($this->items as $item) {
11499 $results[$keyBy($item)] = $item;
11501 return new static($results);
11505 return $this->offsetExists($key);
11509 $first = $this->first();
11510 if (is_array($first) || is_object($first)) {
11511 return implode($glue, $this->lists($value));
11513 return implode($value, $this->items);
11517 return new static(array_intersect($this->items, $this->getArrayableItems($items)));
11521 return empty($this->items);
11525 return !is_string($value) && is_callable($value);
11529 return new static(array_keys($this->items));
11533 return count($this->items) > 0 ? end($this->items) : null;
11537 return array_pluck($this->items, $value, $key);
11539 public function map(callable $callback)
11541 return new static(array_map($callback, $this->items, array_keys($this->items)));
11545 return new static(array_merge($this->items, $this->getArrayableItems($items)));
11549 return new static(array_slice($this->items, ($page - 1) * $perPage, $perPage));
11553 return array_pop($this->items);
11557 array_unshift($this->items, $value);
11561 $this->offsetSet(null, $value);
11563 public function pull($key, $default = null)
11565 return array_pull($this->items, $key, $default);
11569 $this->offsetSet($key, $value);
11576 $keys = array_rand($this->items, $amount);
11577 return is_array($keys) ? array_intersect_key($this->items, array_flip($keys)) : $this->items[$keys];
11579 public function reduce(callable $callback, $initial = null)
11581 return array_reduce($this->items, $callback, $initial);
11585 if ($this->useAsCallable($callback)) {
11586 return $this->
filter(
function ($item) use($callback) {
11587 return !$callback($item);
11590 return $this->
filter(
function ($item) use($callback) {
11591 return $item != $callback;
11596 return new static(array_reverse($this->items));
11600 return array_search($value, $this->items, $strict);
11604 return array_shift($this->items);
11611 public function slice($offset, $length = null, $preserveKeys =
false)
11613 return new static(array_slice($this->items, $offset, $length, $preserveKeys));
11615 public function chunk($size, $preserveKeys =
false)
11618 foreach (array_chunk($this->items, $size, $preserveKeys) as $chunk) {
11619 $chunks[] =
new static($chunk);
11621 return new static($chunks);
11623 public function sort(callable $callback)
11625 uasort($this->items, $callback);
11628 public function sortBy($callback, $options = SORT_REGULAR, $descending =
false)
11630 $results = array();
11631 if (!$this->useAsCallable($callback)) {
11632 $callback = $this->valueRetriever($callback);
11634 foreach ($this->items as $key => $value) {
11635 $results[$key] = $callback($value, $key);
11637 $descending ? arsort($results, $options) : asort($results, $options);
11638 foreach (array_keys($results) as $key) {
11639 $results[$key] = $this->items[$key];
11641 $this->items = $results;
11646 return $this->sortBy($callback, $options,
true);
11648 public function splice($offset, $length = 0, $replacement = array())
11650 return new static(array_splice($this->items, $offset, $length, $replacement));
11652 public function sum($callback = null)
11654 if (is_null($callback)) {
11655 return array_sum($this->items);
11657 if (!$this->useAsCallable($callback)) {
11658 $callback = $this->valueRetriever($callback);
11660 return $this->reduce(
function ($result, $item) use($callback) {
11661 return $result += $callback($item);
11667 return $this->slice($limit, abs($limit));
11669 return $this->slice(0, $limit);
11673 $this->items = array_map($callback, $this->items);
11678 return new static(array_unique($this->items));
11682 return new static(array_values($this->items));
11686 return function ($item) use($value) {
11687 return data_get($item, $value);
11692 return array_map(
function ($value) {
11698 return $this->toArray();
11702 return json_encode($this->toArray(), $options);
11706 return new ArrayIterator($this->items);
11710 return new CachingIterator($this->getIterator(), $flags);
11714 return count($this->items);
11718 return array_key_exists($key, $this->items);
11722 return $this->items[$key];
11726 if (is_null($key)) {
11727 $this->items[] = $value;
11729 $this->items[$key] = $value;
11734 unset($this->items[$key]);
11738 return $this->toJson();
11743 $items = $items->all();
11744 } elseif ($items instanceof
Arrayable) {
11745 $items = $items->toArray();
11757 protected $domain = null;
11758 protected $queued = array();
11759 public function make($name, $value, $minutes = 0,
$path = null, $domain = null, $secure =
false, $httpOnly =
true)
11761 list(
$path, $domain) = $this->getPathAndDomain(
$path, $domain);
11762 $time = $minutes == 0 ? 0 : time() + $minutes * 60;
11763 return new Cookie($name, $value, $time,
$path, $domain, $secure, $httpOnly);
11765 public function forever($name, $value,
$path = null, $domain = null, $secure =
false, $httpOnly =
true)
11767 return $this->make($name, $value, 2628000,
$path, $domain, $secure, $httpOnly);
11771 return $this->make($name, null, -2628000,
$path, $domain);
11775 return !is_null($this->queued($key));
11779 return array_get($this->queued, $key, $default);
11783 if (head(func_get_args()) instanceof
Cookie) {
11784 $cookie = head(func_get_args());
11786 $cookie = call_user_func_array(array($this,
'make'), func_get_args());
11788 $this->queued[$cookie->getName()] = $cookie;
11792 unset($this->queued[$name]);
11796 return array(
$path ?: $this->
path, $domain ?: $this->domain);
11800 list($this->
path, $this->domain) = array(
$path, $domain);
11805 return $this->queued;
11822 $this->encrypter = $encrypter;
11826 return $this->encrypt($next($this->decrypt($request)));
11830 foreach ($request->cookies as $key =>
$c) {
11832 $request->cookies->set($key, $this->decryptCookie(
$c));
11834 $request->cookies->set($key, null);
11841 return is_array($cookie) ? $this->decryptArray($cookie) : $this->encrypter->decrypt($cookie);
11845 $decrypted = array();
11846 foreach ($cookie as $key => $value) {
11847 $decrypted[$key] = $this->encrypter->decrypt($value);
11853 foreach ($response->headers->getCookies() as $key => $cookie) {
11854 $response->headers->setCookie($this->duplicate($cookie, $this->encrypter->encrypt($cookie->getValue())));
11873 $this->cookies = $cookies;
11878 foreach ($this->cookies->getQueuedCookies() as $cookie) {
11879 $response->headers->setCookie($cookie);
11894 protected $cipher = MCRYPT_RIJNDAEL_128;
11895 protected $mode = MCRYPT_MODE_CBC;
11896 protected $block = 16;
11899 $this->key = (string) $key;
11903 $iv = mcrypt_create_iv($this->getIvSize(), $this->getRandomizer());
11904 $value = base64_encode($this->padAndMcrypt($value, $iv));
11905 $mac = $this->hash($iv = base64_encode($iv), $value);
11906 return base64_encode(json_encode(compact(
'iv',
'value',
'mac')));
11910 $value = $this->addPadding(serialize($value));
11911 return mcrypt_encrypt($this->cipher, $this->key, $value, $this->mode, $iv);
11915 $payload = $this->getJsonPayload($payload);
11916 $value = base64_decode($payload[
'value']);
11917 $iv = base64_decode($payload[
'iv']);
11918 return unserialize($this->stripPadding($this->mcryptDecrypt($value, $iv)));
11923 return mcrypt_decrypt($this->cipher, $this->key, $value, $this->mode, $iv);
11924 }
catch (Exception $e) {
11930 $payload = json_decode(base64_decode($payload),
true);
11931 if (!$payload || $this->invalidPayload($payload)) {
11934 if (!$this->validMac($payload)) {
11942 $calcMac = hash_hmac(
'sha256', $this->hash($payload[
'iv'], $payload[
'value']), $bytes,
true);
11943 return StringUtils::equals(hash_hmac(
'sha256', $payload[
'mac'], $bytes,
true), $calcMac);
11947 return hash_hmac(
'sha256', $iv . $value, $this->key);
11951 $pad = $this->block - strlen($value) % $this->block;
11952 return $value . str_repeat(chr($pad), $pad);
11956 $pad = ord($value[($len = strlen($value)) - 1]);
11957 return $this->paddingIsValid($pad, $value) ? substr($value, 0, $len - $pad) : $value;
11961 $beforePad = strlen($value) - $pad;
11962 return substr($value, $beforePad) == str_repeat(substr($value, -1), $pad);
11966 return !is_array($data) || !isset($data[
'iv']) || !isset($data[
'value']) || !isset($data[
'mac']);
11970 return mcrypt_get_iv_size($this->cipher, $this->mode);
11974 if (defined(
'MCRYPT_DEV_URANDOM')) {
11975 return MCRYPT_DEV_URANDOM;
11977 if (defined(
'MCRYPT_DEV_RANDOM')) {
11978 return MCRYPT_DEV_RANDOM;
11981 return MCRYPT_RAND;
11985 $this->key = (string) $key;
11989 $this->cipher = $cipher;
11990 $this->updateBlockSize();
11994 $this->mode = $mode;
11995 $this->updateBlockSize();
11999 $this->block = mcrypt_get_iv_size($this->cipher, $this->mode);
12014 use RuntimeException;
12015 use InvalidArgumentException;
12027 class Writer implements LogContract, PsrLoggerInterface
12031 protected $levels = array(
'debug' => MonologLogger::DEBUG,
'info' => MonologLogger::INFO,
'notice' => MonologLogger::NOTICE,
'warning' => MonologLogger::WARNING,
'error' => MonologLogger::ERROR,
'critical' => MonologLogger::CRITICAL,
'alert' => MonologLogger::ALERT,
'emergency' => MonologLogger::EMERGENCY);
12034 $this->monolog = $monolog;
12035 if (isset($dispatcher)) {
12036 $this->dispatcher = $dispatcher;
12041 return $this->writeLog(__FUNCTION__, $message, $context);
12043 public function alert($message, array $context = array())
12045 return $this->writeLog(__FUNCTION__, $message, $context);
12047 public function critical($message, array $context = array())
12049 return $this->writeLog(__FUNCTION__, $message, $context);
12051 public function error($message, array $context = array())
12053 return $this->writeLog(__FUNCTION__, $message, $context);
12055 public function warning($message, array $context = array())
12057 return $this->writeLog(__FUNCTION__, $message, $context);
12059 public function notice($message, array $context = array())
12061 return $this->writeLog(__FUNCTION__, $message, $context);
12063 public function info($message, array $context = array())
12065 return $this->writeLog(__FUNCTION__, $message, $context);
12067 public function debug($message, array $context = array())
12069 return $this->writeLog(__FUNCTION__, $message, $context);
12071 public function log($level, $message, array $context = array())
12073 return $this->writeLog($level, $message, $context);
12075 public function write($level, $message, array $context = array())
12077 return $this->writeLog($level, $message, $context);
12081 $this->fireLogEvent($level, $message = $this->formatMessage($message), $context);
12082 $this->monolog->{$level}($message, $context);
12086 $this->monolog->pushHandler($handler =
new StreamHandler(
$path, $this->parseLevel($level)));
12087 $handler->setFormatter($this->getDefaultFormatter());
12092 $handler->setFormatter($this->getDefaultFormatter());
12096 return $this->monolog->pushHandler(
new SyslogHandler($name, LOG_USER, $level));
12098 public function useErrorLog($level =
'debug', $messageType = ErrorLogHandler::OPERATING_SYSTEM)
12100 $this->monolog->pushHandler($handler =
new ErrorLogHandler($messageType, $this->parseLevel($level)));
12101 $handler->setFormatter($this->getDefaultFormatter());
12105 if (!isset($this->dispatcher)) {
12106 throw new RuntimeException(
'Events dispatcher has not been set.');
12108 $this->dispatcher->listen(
'illuminate.log', $callback);
12112 if (isset($this->dispatcher)) {
12113 $this->dispatcher->fire(
'illuminate.log', compact(
'level',
'message',
'context'));
12118 if (is_array($message)) {
12119 return var_export($message,
true);
12120 } elseif ($message instanceof
Jsonable) {
12121 return $message->toJson();
12122 } elseif ($message instanceof
Arrayable) {
12123 return var_export($message->toArray(),
true);
12129 if (isset($this->levels[$level])) {
12130 return $this->levels[$level];
12132 throw new InvalidArgumentException(
'Invalid log level.');
12136 return $this->monolog;
12144 return $this->dispatcher;
12148 $this->dispatcher = $dispatcher;
12162 $this->view = $view;
12166 if ($request->session()->has(
'errors')) {
12167 $this->view->share(
'errors', $request->session()->get(
'errors'));
12171 return $next($request);
12184 const NOTICE = 250;
12185 const WARNING = 300;
12187 const CRITICAL = 500;
12189 const EMERGENCY = 600;
12191 protected static $levels = array(100 =>
'DEBUG', 200 =>
'INFO', 250 =>
'NOTICE', 300 =>
'WARNING', 400 =>
'ERROR', 500 =>
'CRITICAL', 550 =>
'ALERT', 600 =>
'EMERGENCY');
12196 public function __construct($name, array $handlers = array(), array $processors = array())
12198 $this->
name = $name;
12199 $this->handlers = $handlers;
12200 $this->processors = $processors;
12204 return $this->name;
12208 array_unshift($this->handlers, $handler);
12212 if (!$this->handlers) {
12213 throw new \LogicException(
'You tried to pop from an empty handler stack.');
12215 return array_shift($this->handlers);
12219 return $this->handlers;
12223 if (!is_callable($callback)) {
12224 throw new \InvalidArgumentException(
'Processors must be valid callables (callback or object with an __invoke method), ' . var_export($callback,
true) .
' given');
12226 array_unshift($this->processors, $callback);
12230 if (!$this->processors) {
12231 throw new \LogicException(
'You tried to pop from an empty processor stack.');
12233 return array_shift($this->processors);
12237 return $this->processors;
12239 public function addRecord($level, $message, array $context = array())
12241 if (!$this->handlers) {
12242 $this->pushHandler(
new StreamHandler(
'php://stderr', static::DEBUG));
12244 $levelName = static::getLevelName($level);
12245 $handlerKey = null;
12246 foreach ($this->handlers as $key => $handler) {
12247 if ($handler->isHandling(array(
'level' => $level))) {
12248 $handlerKey = $key;
12252 if (null === $handlerKey) {
12255 if (!static::$timezone) {
12256 static::$timezone = new \DateTimeZone(date_default_timezone_get() ?:
'UTC');
12258 $record = array(
'message' => (
string) $message,
'context' => $context,
'level' => $level,
'level_name' => $levelName,
'channel' => $this->
name,
'datetime' => \DateTime::createFromFormat(
'U.u', sprintf(
'%.6F', microtime(
true)), static::$timezone)->setTimezone(static::$timezone),
'extra' => array());
12259 foreach ($this->processors as $processor) {
12260 $record = call_user_func($processor, $record);
12262 while (isset($this->handlers[$handlerKey]) &&
false === $this->handlers[$handlerKey]->handle($record)) {
12267 public function addDebug($message, array $context = array())
12269 return $this->addRecord(static::DEBUG, $message, $context);
12271 public function addInfo($message, array $context = array())
12273 return $this->addRecord(static::INFO, $message, $context);
12277 return $this->addRecord(static::NOTICE, $message, $context);
12281 return $this->addRecord(static::WARNING, $message, $context);
12283 public function addError($message, array $context = array())
12285 return $this->addRecord(static::ERROR, $message, $context);
12289 return $this->addRecord(static::CRITICAL, $message, $context);
12291 public function addAlert($message, array $context = array())
12293 return $this->addRecord(static::ALERT, $message, $context);
12297 return $this->addRecord(static::EMERGENCY, $message, $context);
12301 return array_flip(static::$levels);
12305 if (!isset(static::$levels[$level])) {
12306 throw new InvalidArgumentException(
'Level "' . $level .
'" is not defined, use one of: ' . implode(
', ', array_keys(static::$levels)));
12308 return static::$levels[$level];
12312 if (is_string($level) && defined(__CLASS__ .
'::' . strtoupper($level))) {
12313 return constant(__CLASS__ .
'::' . strtoupper($level));
12319 $record = array(
'level' => $level);
12320 foreach ($this->handlers as $handler) {
12321 if ($handler->isHandling($record)) {
12327 public function log($level, $message, array $context = array())
12329 if (is_string($level) && defined(__CLASS__ .
'::' . strtoupper($level))) {
12330 $level = constant(__CLASS__ .
'::' . strtoupper($level));
12332 return $this->addRecord($level, $message, $context);
12334 public function debug($message, array $context = array())
12336 return $this->addRecord(static::DEBUG, $message, $context);
12338 public function info($message, array $context = array())
12340 return $this->addRecord(static::INFO, $message, $context);
12342 public function notice($message, array $context = array())
12344 return $this->addRecord(static::NOTICE, $message, $context);
12346 public function warn($message, array $context = array())
12348 return $this->addRecord(static::WARNING, $message, $context);
12350 public function warning($message, array $context = array())
12352 return $this->addRecord(static::WARNING, $message, $context);
12354 public function err($message, array $context = array())
12356 return $this->addRecord(static::ERROR, $message, $context);
12358 public function error($message, array $context = array())
12360 return $this->addRecord(static::ERROR, $message, $context);
12362 public function crit($message, array $context = array())
12364 return $this->addRecord(static::CRITICAL, $message, $context);
12366 public function critical($message, array $context = array())
12368 return $this->addRecord(static::CRITICAL, $message, $context);
12370 public function alert($message, array $context = array())
12372 return $this->addRecord(static::ALERT, $message, $context);
12374 public function emerg($message, array $context = array())
12376 return $this->addRecord(static::EMERGENCY, $message, $context);
12380 return $this->addRecord(static::EMERGENCY, $message, $context);
12387 public function emergency($message, array $context = array());
12388 public function alert($message, array $context = array());
12389 public function critical($message, array $context = array());
12390 public function error($message, array $context = array());
12391 public function warning($message, array $context = array());
12392 public function notice($message, array $context = array());
12393 public function info($message, array $context = array());
12394 public function debug($message, array $context = array());
12395 public function log($level, $message, array $context = array());
12404 protected $level = Logger::DEBUG;
12405 protected $bubble =
true;
12407 protected $processors = array();
12410 $this->setLevel($level);
12411 $this->bubble = $bubble;
12415 return $record[
'level'] >= $this->level;
12419 foreach ($records as $record) {
12420 $this->handle($record);
12428 if (!is_callable($callback)) {
12429 throw new \InvalidArgumentException(
'Processors must be valid callables (callback or object with an __invoke method), ' . var_export($callback,
true) .
' given');
12431 array_unshift($this->processors, $callback);
12436 if (!$this->processors) {
12437 throw new \LogicException(
'You tried to pop from an empty processor stack.');
12439 return array_shift($this->processors);
12443 $this->formatter = $formatter;
12448 if (!$this->formatter) {
12449 $this->formatter = $this->getDefaultFormatter();
12451 return $this->formatter;
12455 $this->level = Logger::toMonologLevel($level);
12460 return $this->level;
12464 $this->bubble = $bubble;
12469 return $this->bubble;
12475 }
catch (\Exception $e) {
12489 if (!$this->isHandling($record)) {
12492 $record = $this->processRecord($record);
12493 $record[
'formatted'] = $this->getFormatter()->format($record);
12494 $this->write($record);
12495 return false === $this->bubble;
12497 protected abstract function write(array $record);
12500 if ($this->processors) {
12501 foreach ($this->processors as $processor) {
12502 $record = call_user_func($processor, $record);
12515 private $errorMessage;
12518 public function __construct($stream, $level = Logger::DEBUG, $bubble =
true, $filePermission = null, $useLocking =
false)
12520 parent::__construct($level, $bubble);
12521 if (is_resource($stream)) {
12522 $this->
stream = $stream;
12523 } elseif (is_string($stream)) {
12524 $this->
url = $stream;
12526 throw new \InvalidArgumentException(
'A stream must either be a resource or a string.');
12528 $this->filePermission = $filePermission;
12529 $this->useLocking = $useLocking;
12533 if (is_resource($this->
stream)) {
12540 if (!is_resource($this->
stream)) {
12542 throw new \LogicException(
'Missing stream url, the stream can not be opened. This may be caused by a premature call to close().');
12544 $this->errorMessage = null;
12545 set_error_handler(array($this,
'customErrorHandler'));
12546 $this->
stream = fopen($this->
url,
'a');
12547 if ($this->filePermission !== null) {
12548 @chmod($this->
url, $this->filePermission);
12550 restore_error_handler();
12551 if (!is_resource($this->
stream)) {
12553 throw new \UnexpectedValueException(sprintf(
'The stream or file "%s" could not be opened: ' . $this->errorMessage, $this->
url));
12556 if ($this->useLocking) {
12557 flock($this->
stream, LOCK_EX);
12559 fwrite($this->
stream, (
string) $record[
'formatted']);
12560 if ($this->useLocking) {
12561 flock($this->
stream, LOCK_UN);
12564 private function customErrorHandler(
$code, $msg)
12566 $this->errorMessage = preg_replace(
'{^fopen\\(.*?\\): }',
'', $msg);
12580 public function __construct($filename, $maxFiles = 0, $level = Logger::DEBUG, $bubble =
true, $filePermission = null, $useLocking =
false)
12582 $this->filename = $filename;
12583 $this->maxFiles = (int) $maxFiles;
12584 $this->nextRotation = new \DateTime(
'tomorrow');
12585 $this->filenameFormat =
'{filename}-{date}';
12586 $this->dateFormat =
'Y-m-d';
12587 parent::__construct($this->getTimedFilename(), $level, $bubble, $filePermission, $useLocking);
12592 if (
true === $this->mustRotate) {
12598 $this->filenameFormat = $filenameFormat;
12599 $this->dateFormat = $dateFormat;
12600 $this->
url = $this->getTimedFilename();
12605 if (null === $this->mustRotate) {
12606 $this->mustRotate = !file_exists($this->
url);
12608 if ($this->nextRotation < $record[
'datetime']) {
12609 $this->mustRotate =
true;
12612 parent::write($record);
12616 $this->
url = $this->getTimedFilename();
12617 $this->nextRotation = new \DateTime(
'tomorrow');
12618 if (0 === $this->maxFiles) {
12621 $logFiles = glob($this->getGlobPattern());
12622 if ($this->maxFiles >= count($logFiles)) {
12625 usort($logFiles,
function (
$a,
$b) {
12626 return strcmp(
$b,
$a);
12628 foreach (array_slice($logFiles, $this->maxFiles) as $file) {
12629 if (is_writable($file)) {
12636 $fileInfo = pathinfo($this->filename);
12637 $timedFilename = str_replace(array(
'{filename}',
'{date}'), array($fileInfo[
'filename'], date($this->dateFormat)), $fileInfo[
'dirname'] .
'/' . $this->filenameFormat);
12638 if (!
empty($fileInfo[
'extension'])) {
12639 $timedFilename .=
'.' . $fileInfo[
'extension'];
12641 return $timedFilename;
12645 $fileInfo = pathinfo($this->filename);
12646 $glob = str_replace(array(
'{filename}',
'{date}'), array($fileInfo[
'filename'],
'*'), $fileInfo[
'dirname'] .
'/' . $this->filenameFormat);
12647 if (!
empty($fileInfo[
'extension'])) {
12648 $glob .=
'.' . $fileInfo[
'extension'];
12658 public function isHandling(array $record);
12659 public function handle(array $record);
12660 public function handleBatch(array $records);
12661 public function pushProcessor($callback);
12662 public function popProcessor();
12664 public function getFormatter();
12670 public function format(array $record);
12671 public function formatBatch(array $records);
12678 const SIMPLE_DATE =
'Y-m-d H:i:s';
12682 $this->dateFormat = $dateFormat ?: static::SIMPLE_DATE;
12683 if (!function_exists(
'json_encode')) {
12684 throw new \RuntimeException(
'PHP\'s json extension is required to use Monolog\'s NormalizerFormatter');
12689 return $this->normalize($record);
12693 foreach ($records as $key => $record) {
12694 $records[$key] = $this->
format($record);
12700 if (null === $data || is_scalar($data)) {
12701 if (is_float($data)) {
12702 if (is_infinite($data)) {
12703 return ($data > 0 ?
'' :
'-') .
'INF';
12705 if (is_nan($data)) {
12711 if (is_array($data) || $data instanceof \Traversable) {
12712 $normalized = array();
12714 foreach ($data as $key => $value) {
12716 $normalized[
'...'] =
'Over 1000 items, aborting normalization';
12719 $normalized[$key] = $this->normalize($value);
12721 return $normalized;
12723 if ($data instanceof \DateTime) {
12724 return $data->format($this->dateFormat);
12726 if (is_object($data)) {
12727 if ($data instanceof Exception) {
12728 return $this->normalizeException($data);
12730 return sprintf(
'[object] (%s: %s)', get_class($data), $this->toJson($data,
true));
12732 if (is_resource($data)) {
12733 return '[resource]';
12735 return '[unknown(' . gettype($data) .
')]';
12739 $data = array(
'class' => get_class($e),
'message' => $e->getMessage(),
'code' => $e->getCode(),
'file' => $e->getFile() .
':' . $e->getLine());
12740 $trace = $e->getTrace();
12741 foreach ($trace as $frame) {
12742 if (isset($frame[
'file'])) {
12743 $data[
'trace'][] = $frame[
'file'] .
':' . $frame[
'line'];
12745 $data[
'trace'][] = $this->toJson($this->normalize($frame),
true);
12748 if ($previous = $e->getPrevious()) {
12749 $data[
'previous'] = $this->normalizeException($previous);
12753 protected function toJson($data, $ignoreErrors =
false)
12755 if ($ignoreErrors) {
12756 if (version_compare(PHP_VERSION,
'5.4.0',
'>=')) {
12757 return @json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
12759 return @json_encode($data);
12761 if (version_compare(PHP_VERSION,
'5.4.0',
'>=')) {
12762 return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
12764 return json_encode($data);
12772 const SIMPLE_FORMAT =
'[%datetime%] %channel%.%level_name%: %message% %context% %extra%
12778 public function __construct($format = null, $dateFormat = null, $allowInlineLineBreaks =
false, $ignoreEmptyContextAndExtra =
false)
12780 $this->
format = $format ?: static::SIMPLE_FORMAT;
12781 $this->allowInlineLineBreaks = $allowInlineLineBreaks;
12782 $this->ignoreEmptyContextAndExtra = $ignoreEmptyContextAndExtra;
12783 parent::__construct($dateFormat);
12787 $this->includeStacktraces = $include;
12788 if ($this->includeStacktraces) {
12789 $this->allowInlineLineBreaks =
true;
12794 $this->allowInlineLineBreaks = $allow;
12798 $this->ignoreEmptyContextAndExtra = $ignore;
12804 foreach ($vars[
'extra'] as
$var => $val) {
12805 if (
false !== strpos(
$output,
'%extra.' .
$var .
'%')) {
12807 unset($vars[
'extra'][
$var]);
12810 if ($this->ignoreEmptyContextAndExtra) {
12811 if (
empty($vars[
'context'])) {
12812 unset($vars[
'context']);
12815 if (
empty($vars[
'extra'])) {
12816 unset($vars[
'extra']);
12820 foreach ($vars as
$var => $val) {
12821 if (
false !== strpos(
$output,
'%' .
$var .
'%')) {
12830 foreach ($records as $record) {
12831 $message .= $this->
format($record);
12837 return $this->replaceNewlines($this->convertToString($value));
12841 $previousText =
'';
12842 if ($previous = $e->getPrevious()) {
12844 $previousText .=
', ' . get_class($previous) .
'(code: ' . $previous->getCode() .
'): ' . $previous->getMessage() .
' at ' . $previous->getFile() .
':' . $previous->getLine();
12845 }
while ($previous = $previous->getPrevious());
12847 $str =
'[object] (' . get_class($e) .
'(code: ' . $e->getCode() .
'): ' . $e->getMessage() .
' at ' . $e->getFile() .
':' . $e->getLine() . $previousText .
')';
12848 if ($this->includeStacktraces) {
12851 ' . $e->getTraceAsString();
12857 if (null === $data || is_bool($data)) {
12858 return var_export($data,
true);
12860 if (is_scalar($data)) {
12861 return (
string) $data;
12863 if (version_compare(PHP_VERSION,
'5.4.0',
'>=')) {
12864 return $this->toJson($data,
true);
12866 return str_replace(
'\\/',
'/', @json_encode($data));
12870 if ($this->allowInlineLineBreaks) {
12873 return strtr($str, array(
'
12900 use InvalidArgumentException;
12903 protected $resolvers = array();
12904 protected $resolved = array();
12905 public function register($engine, Closure $resolver)
12907 unset($this->resolved[$engine]);
12908 $this->resolvers[$engine] = $resolver;
12912 if (isset($this->resolved[$engine])) {
12913 return $this->resolved[$engine];
12915 if (isset($this->resolvers[$engine])) {
12916 return $this->resolved[$engine] = call_user_func($this->resolvers[$engine]);
12918 throw new InvalidArgumentException(
"Engine {$engine} not found.");
12925 const HINT_PATH_DELIMITER =
'::';
12926 public function find($view);
12927 public function addLocation($location);
12928 public function addNamespace($namespace, $hints);
12929 public function prependNamespace($namespace, $hints);
12930 public function addExtension($extension);
12934 use InvalidArgumentException;
12940 protected $views = array();
12941 protected $hints = array();
12942 protected $extensions = array(
'blade.php',
'php');
12945 $this->files = $files;
12946 $this->paths = $paths;
12947 if (isset($extensions)) {
12948 $this->extensions = $extensions;
12953 if (isset($this->views[$name])) {
12954 return $this->views[$name];
12956 if ($this->hasHintInformation($name = trim($name))) {
12957 return $this->views[$name] = $this->findNamedPathView($name);
12959 return $this->views[$name] = $this->findInPaths($name, $this->paths);
12963 list($namespace, $view) = $this->getNamespaceSegments($name);
12964 return $this->findInPaths($view, $this->hints[$namespace]);
12968 $segments = explode(static::HINT_PATH_DELIMITER, $name);
12969 if (count($segments) != 2) {
12970 throw new InvalidArgumentException(
"View [{$name}] has an invalid name.");
12972 if (!isset($this->hints[$segments[0]])) {
12973 throw new InvalidArgumentException(
"No hint path defined for [{$segments[0]}].");
12979 foreach ((array) $paths as
$path) {
12980 foreach ($this->getPossibleViewFiles($name) as $file) {
12981 if ($this->files->exists($viewPath = $path .
'/' . $file)) {
12986 throw new InvalidArgumentException(
"View [{$name}] not found.");
12990 return array_map(
function ($extension) use($name) {
12991 return str_replace(
'.',
'/', $name) .
'.' . $extension;
12992 }, $this->extensions);
12996 $this->paths[] = $location;
13000 $hints = (array) $hints;
13001 if (isset($this->hints[$namespace])) {
13002 $hints = array_merge($this->hints[$namespace], $hints);
13004 $this->hints[$namespace] = $hints;
13008 $hints = (array) $hints;
13009 if (isset($this->hints[$namespace])) {
13010 $hints = array_merge($hints, $this->hints[$namespace]);
13012 $this->hints[$namespace] = $hints;
13016 if (($index = array_search($extension, $this->extensions)) !==
false) {
13017 unset($this->extensions[$index]);
13019 array_unshift($this->extensions, $extension);
13023 return strpos($name, static::HINT_PATH_DELIMITER) > 0;
13027 return $this->files;
13031 return $this->paths;
13035 return $this->hints;
13039 return $this->extensions;
13045 use InvalidArgumentException;
13057 protected $shared = array();
13058 protected $aliases = array();
13059 protected $names = array();
13060 protected $extensions = array(
'blade.php' =>
'blade',
'php' =>
'php');
13061 protected $composers = array();
13062 protected $sections = array();
13063 protected $sectionStack = array();
13064 protected $renderCount = 0;
13067 $this->finder = $finder;
13068 $this->events = $events;
13069 $this->engines = $engines;
13070 $this->share(
'__env', $this);
13072 public function file(
$path, $data = array(), $mergeData = array())
13074 $data = array_merge($mergeData, $this->parseData($data));
13075 $this->callCreator($view =
new View($this, $this->getEngineFromPath(
$path),
$path,
$path, $data));
13078 public function make($view, $data = array(), $mergeData = array())
13080 if (isset($this->aliases[$view])) {
13081 $view = $this->aliases[$view];
13083 $view = $this->normalizeName($view);
13084 $path = $this->finder->find($view);
13085 $data = array_merge($mergeData, $this->parseData($data));
13086 $this->callCreator($view =
new View($this, $this->getEngineFromPath(
$path), $view,
$path, $data));
13091 $delimiter = ViewFinderInterface::HINT_PATH_DELIMITER;
13092 if (strpos($name, $delimiter) ===
false) {
13093 return str_replace(
'/',
'.', $name);
13095 list($namespace, $name) = explode($delimiter, $name);
13096 return $namespace . $delimiter . str_replace(
'/',
'.', $name);
13102 public function of($view, $data = array())
13104 return $this->make($this->names[$view], $data);
13108 $this->names[$name] = $view;
13112 $this->aliases[$alias] = $view;
13117 $this->finder->find($view);
13118 }
catch (InvalidArgumentException $e) {
13126 if (count($data) > 0) {
13127 foreach ($data as $key => $value) {
13128 $data = array(
'key' => $key, $iterator => $value);
13129 $result .= $this->make($view, $data)->render();
13132 if (starts_with($empty,
'raw|')) {
13133 $result = substr($empty, 4);
13135 $result = $this->make($empty)->render();
13142 if (!($extension = $this->getExtension(
$path))) {
13143 throw new InvalidArgumentException(
"Unrecognized extension in file: {$path}");
13145 $engine = $this->extensions[$extension];
13146 return $this->engines->resolve($engine);
13150 $extensions = array_keys($this->extensions);
13151 return array_first($extensions,
function ($key, $value) use(
$path) {
13152 return ends_with(
$path, $value);
13157 if (!is_array($key)) {
13158 return $this->shared[$key] = $value;
13160 foreach ($key as $innerKey => $innerValue) {
13161 $this->share($innerKey, $innerValue);
13166 $creators = array();
13167 foreach ((array) $views as $view) {
13168 $creators[] = $this->addViewEvent($view, $callback,
'creating: ');
13174 $registered = array();
13175 foreach ($composers as $callback => $views) {
13176 $registered = array_merge($registered, $this->composer($views, $callback));
13178 return $registered;
13180 public function composer($views, $callback, $priority = null)
13182 $composers = array();
13183 foreach ((array) $views as $view) {
13184 $composers[] = $this->addViewEvent($view, $callback,
'composing: ', $priority);
13188 protected function addViewEvent($view, $callback, $prefix =
'composing: ', $priority = null)
13190 $view = $this->normalizeName($view);
13191 if ($callback instanceof Closure) {
13192 $this->addEventListener($prefix . $view, $callback, $priority);
13194 } elseif (is_string($callback)) {
13195 return $this->addClassEvent($view, $callback, $prefix, $priority);
13200 $name = $prefix . $view;
13201 $callback = $this->buildClassEventCallback($class, $prefix);
13202 $this->addEventListener($name, $callback, $priority);
13207 if (is_null($priority)) {
13208 $this->events->listen($name, $callback);
13210 $this->events->listen($name, $callback, $priority);
13215 list($class, $method) = $this->parseClassEvent($class, $prefix);
13216 return function () use($class, $method) {
13217 $callable = array($this->container->make($class), $method);
13218 return call_user_func_array($callable, func_get_args());
13223 if (str_contains($class,
'@')) {
13224 return explode(
'@', $class);
13226 $method = str_contains($prefix,
'composing') ?
'compose' :
'create';
13227 return array($class, $method);
13231 $this->events->fire(
'composing: ' . $view->
getName(), array($view));
13235 $this->events->fire(
'creating: ' . $view->
getName(), array($view));
13239 if ($content ===
'') {
13241 $this->sectionStack[] = $section;
13244 $this->extendSection($section, $content);
13249 return $this->startSection($section, $content);
13253 return $this->yieldContent($this->stopSection());
13257 $last = array_pop($this->sectionStack);
13259 $this->sections[$last] = ob_get_clean();
13261 $this->extendSection($last, ob_get_clean());
13267 $last = array_pop($this->sectionStack);
13268 if (isset($this->sections[$last])) {
13269 $this->sections[$last] .= ob_get_clean();
13271 $this->sections[$last] = ob_get_clean();
13277 if (isset($this->sections[$section])) {
13278 $content = str_replace(
'@parent', $content, $this->sections[$section]);
13280 $this->sections[$section] = $content;
13284 $sectionContent = $default;
13285 if (isset($this->sections[$section])) {
13286 $sectionContent = $this->sections[$section];
13288 $sectionContent = str_replace(
'@@parent',
'--parent--holder--', $sectionContent);
13289 return str_replace(
'--parent--holder--',
'@parent', str_replace(
'@parent',
'', $sectionContent));
13293 $this->sections = array();
13294 $this->sectionStack = array();
13298 if ($this->doneRendering()) {
13299 $this->flushSections();
13304 $this->renderCount++;
13308 $this->renderCount--;
13312 return $this->renderCount == 0;
13316 $this->finder->addLocation($location);
13320 $this->finder->addNamespace($namespace, $hints);
13324 $this->finder->prependNamespace($namespace, $hints);
13328 $this->finder->addExtension($extension);
13329 if (isset($resolver)) {
13330 $this->engines->register($engine, $resolver);
13332 unset($this->extensions[$extension]);
13333 $this->extensions = array_merge(array($extension => $engine), $this->extensions);
13337 return $this->extensions;
13341 return $this->engines;
13345 return $this->finder;
13349 $this->finder = $finder;
13353 return $this->events;
13357 $this->events = $events;
13369 return array_get($this->shared, $key, $default);
13373 return $this->shared;
13377 return $this->sections;
13381 return $this->names;
13390 protected $bags = array();
13393 return isset($this->bags[$key]);
13397 return array_get($this->bags, $key,
new MessageBag());
13401 return $this->bags;
13403 public function put($key, MessageBagContract $bag)
13405 $this->bags[$key] = $bag;
13410 return $this->
default->count();
13414 return call_user_func_array(array($this->
default, $method), $parameters);
13418 return array_get($this->bags, $key,
new MessageBag());
13422 array_set($this->bags, $key, $value);
13428 use JsonSerializable;
13435 protected $messages = array();
13436 protected $format =
':message';
13439 foreach ($messages as $key => $value) {
13440 $this->messages[$key] = (array) $value;
13445 return array_keys($this->messages);
13447 public function add($key, $message)
13449 if ($this->isUnique($key, $message)) {
13450 $this->messages[$key][] = $message;
13457 $messages = $messages->getMessageBag()->getMessages();
13459 $this->messages = array_merge_recursive($this->messages, $messages);
13464 $messages = (array) $this->messages;
13465 return !isset($messages[$key]) || !in_array($message, $messages[$key]);
13469 return $this->first($key) !==
'';
13471 public function first($key = null, $format = null)
13473 $messages = is_null($key) ? $this->all($format) : $this->
get($key, $format);
13474 return count($messages) > 0 ? $messages[0] :
'';
13476 public function get($key, $format = null)
13478 $format = $this->checkFormat($format);
13479 if (array_key_exists($key, $this->messages)) {
13480 return $this->
transform($this->messages[$key], $format, $key);
13484 public function all($format = null)
13486 $format = $this->checkFormat($format);
13488 foreach ($this->messages as $key => $messages) {
13489 $all = array_merge($all, $this->
transform($messages, $format, $key));
13495 $messages = (array) $messages;
13496 foreach ($messages as &$message) {
13497 $replace = array(
':message',
':key');
13498 $message = str_replace($replace, array($message, $messageKey), $format);
13504 return $format ?: $this->format;
13508 return $this->messages;
13516 return $this->format;
13520 $this->
format = $format;
13525 return !$this->
any();
13529 return $this->count() > 0;
13533 return count($this->messages, COUNT_RECURSIVE) - count($this->messages);
13537 return $this->getMessages();
13541 return $this->toArray();
13545 return json_encode($this->toArray(), $options);
13549 return $this->toJson();
13565 use BadMethodCallException;
13572 class View implements ArrayAccess, ViewContract
13581 $this->view = $view;
13583 $this->engine = $engine;
13589 $contents = $this->renderContents();
13590 $response = isset($callback) ? $callback($this, $contents) : null;
13591 $this->
factory->flushSectionsIfDoneRendering();
13596 $this->
factory->incrementRender();
13597 $this->
factory->callComposer($this);
13598 $contents = $this->getContents();
13599 $this->
factory->decrementRender();
13604 $env = $this->factory;
13605 return $this->
render(
function ($view) use($env) {
13606 return $env->getSections();
13611 return $this->engine->get($this->
path, $this->gatherData());
13615 $data = array_merge($this->
factory->getShared(), $this->data);
13616 foreach ($data as $key => $value) {
13618 $data[$key] = $value->render();
13623 public function with($key, $value = null)
13625 if (is_array($key)) {
13626 $this->
data = array_merge($this->
data, $key);
13628 $this->
data[$key] = $value;
13632 public function nest($key, $view, array $data = array())
13634 return $this->with($key, $this->
factory->make($view, $data));
13639 $this->with(
'errors', $provider->getMessageBag());
13641 $this->with(
'errors',
new MessageBag((array) $provider));
13647 return $this->factory;
13651 return $this->engine;
13655 return $this->getName();
13659 return $this->view;
13663 return $this->data;
13675 return array_key_exists($key, $this->
data);
13679 return $this->
data[$key];
13683 $this->with($key, $value);
13687 unset($this->
data[$key]);
13691 return $this->
data[$key];
13695 $this->with($key, $value);
13699 return isset($this->
data[$key]);
13703 unset($this->
data[$key]);
13707 if (starts_with($method,
'with')) {
13708 return $this->with(snake_case(substr($method, 4)), $parameters[0]);
13710 throw new BadMethodCallException(
"Method [{$method}] does not exist on view.");
13721 public function get(
$path, array $data = array());
13728 public function get(
$path, array $data = array())
13730 return $this->evaluatePath(
$path, $data);
13734 $obLevel = ob_get_level();
13739 }
catch (Exception $e) {
13740 $this->handleViewException($e, $obLevel);
13742 return ltrim(ob_get_clean());
13746 while (ob_get_level() > $obLevel) {
13754 use ErrorException;
13759 protected $lastCompiled = array();
13762 $this->compiler = $compiler;
13764 public function get(
$path, array $data = array())
13766 $this->lastCompiled[] =
$path;
13767 if ($this->compiler->isExpired(
$path)) {
13768 $this->compiler->compile(
$path);
13770 $compiled = $this->compiler->getCompiledPath(
$path);
13771 $results = $this->evaluatePath($compiled, $data);
13772 array_pop($this->lastCompiled);
13777 $e =
new ErrorException($this->getMessage($e), 0, 1, $e->getFile(), $e->getLine(), $e);
13778 parent::handleViewException($e, $obLevel);
13782 return $e->getMessage() .
' (View: ' . realpath(last($this->lastCompiled)) .
')';
13786 return $this->compiler;
13793 public function getCompiledPath(
$path);
13794 public function isExpired(
$path);
13795 public function compile(
$path);
13806 $this->files = $files;
13807 $this->cachePath = $cachePath;
13811 return $this->cachePath .
'/' . md5(
$path);
13815 $compiled = $this->getCompiledPath(
$path);
13816 if (!$this->cachePath || !$this->files->exists($compiled)) {
13819 $lastModified = $this->files->lastModified(
$path);
13820 return $lastModified >= $this->files->lastModified($compiled);
13827 protected $extensions = array();
13829 protected $compilers = array(
'Extensions',
'Statements',
'Comments',
'Echos');
13830 protected $rawTags = array(
'{!!',
'!!}');
13831 protected $contentTags = array(
'{{',
'}}');
13832 protected $escapedTags = array(
'{{{',
'}}}');
13833 protected $echoFormat =
'e(%s)';
13834 protected $footer = array();
13835 protected $forelseCounter = 0;
13838 $this->footer = array();
13840 $this->setPath(
$path);
13842 $contents = $this->compileString($this->files->get(
$path));
13843 if (!is_null($this->cachePath)) {
13844 $this->files->put($this->getCompiledPath($this->getPath()), $contents);
13858 foreach (token_get_all($value) as $token) {
13859 $result .= is_array($token) ? $this->parseToken($token) : $token;
13861 if (count($this->footer) > 0) {
13862 $result = ltrim($result, PHP_EOL) . PHP_EOL . implode(PHP_EOL, array_reverse($this->footer));
13868 list($id, $content) = $token;
13869 if ($id == T_INLINE_HTML) {
13870 foreach ($this->compilers as $type) {
13871 $content = $this->{
"compile{$type}"}($content);
13878 foreach ($this->extensions as $compiler) {
13879 $value = call_user_func($compiler, $value, $this);
13885 $pattern = sprintf(
'/%s--((.|\\s)*?)--%s/', $this->contentTags[0], $this->contentTags[1]);
13886 return preg_replace($pattern,
'<?php /*$1*/ ?>', $value);
13890 foreach ($this->getEchoMethods() as $method => $length) {
13891 $value = $this->{$method}($value);
13897 $methods = array(
'compileRawEchos' => strlen(stripcslashes($this->rawTags[0])),
'compileEscapedEchos' => strlen(stripcslashes($this->escapedTags[0])),
'compileRegularEchos' => strlen(stripcslashes($this->contentTags[0])));
13898 uksort($methods,
function ($method1, $method2) use($methods) {
13899 if ($methods[$method1] > $methods[$method2]) {
13902 if ($methods[$method1] < $methods[$method2]) {
13905 if ($method1 ===
'compileRawEchos') {
13908 if ($method2 ===
'compileRawEchos') {
13911 if ($method1 ===
'compileEscapedEchos') {
13914 if ($method2 ===
'compileEscapedEchos') {
13922 $callback =
function ($match) {
13923 if (method_exists($this, $method =
'compile' . ucfirst($match[1]))) {
13924 $match[0] = $this->{$method}(array_get($match, 3));
13926 return isset($match[3]) ? $match[0] : $match[0] . $match[2];
13928 return preg_replace_callback(
'/\\B@(\\w+)([ \\t]*)(\\( ( (?>[^()]+) | (?3) )* \\))?/x', $callback, $value);
13932 $pattern = sprintf(
'/(@)?%s\\s*(.+?)\\s*%s(\\r?\\n)?/s', $this->rawTags[0], $this->rawTags[1]);
13933 $callback =
function ($matches) {
13934 $whitespace =
empty($matches[3]) ?
'' : $matches[3] . $matches[3];
13935 return $matches[1] ? substr($matches[0], 1) :
'<?php echo ' . $this->compileEchoDefaults($matches[2]) .
'; ?>' . $whitespace;
13937 return preg_replace_callback($pattern, $callback, $value);
13941 $pattern = sprintf(
'/(@)?%s\\s*(.+?)\\s*%s(\\r?\\n)?/s', $this->contentTags[0], $this->contentTags[1]);
13942 $callback =
function ($matches) {
13943 $whitespace =
empty($matches[3]) ?
'' : $matches[3] . $matches[3];
13944 $wrapped = sprintf($this->echoFormat, $this->compileEchoDefaults($matches[2]));
13945 return $matches[1] ? substr($matches[0], 1) :
'<?php echo ' . $wrapped .
'; ?>' . $whitespace;
13947 return preg_replace_callback($pattern, $callback, $value);
13951 $pattern = sprintf(
'/%s\\s*(.+?)\\s*%s(\\r?\\n)?/s', $this->escapedTags[0], $this->escapedTags[1]);
13952 $callback =
function ($matches) {
13953 $whitespace =
empty($matches[2]) ?
'' : $matches[2] . $matches[2];
13954 return '<?php echo e(' . $this->compileEchoDefaults($matches[1]) .
'); ?>' . $whitespace;
13956 return preg_replace_callback($pattern, $callback, $value);
13960 return preg_replace(
'/^(?=\\$)(.+?)(?:\\s+or\\s+)(.+?)$/s',
'isset($1) ? $1 : $2', $value);
13964 return "<?php echo \$__env->renderEach{$expression}; ?>";
13968 return "<?php echo \$__env->yieldContent{$expression}; ?>";
13972 return '<?php echo $__env->yieldSection(); ?>';
13976 return "<?php \$__env->startSection{$expression}; ?>";
13980 return '<?php $__env->appendSection(); ?>';
13984 return '<?php $__env->stopSection(); ?>';
13988 return '<?php $__env->stopSection(); ?>';
13992 return '<?php $__env->stopSection(true); ?>';
13996 return "<?php if ( ! {$expression}): ?>";
14000 return '<?php endif; ?>';
14004 return "<?php echo \\Illuminate\\Support\\Facades\\Lang::get{$expression}; ?>";
14008 return "<?php echo \\Illuminate\\Support\\Facades\\Lang::choice{$expression}; ?>";
14012 return '<?php else: ?>';
14016 return "<?php for{$expression}: ?>";
14020 return "<?php foreach{$expression}: ?>";
14024 $empty =
'$__empty_' . ++$this->forelseCounter;
14025 return "<?php {$empty} = true; foreach{$expression}: {$empty} = false; ?>";
14029 return "<?php if{$expression}: ?>";
14033 return "<?php elseif{$expression}: ?>";
14037 $empty =
'$__empty_' . $this->forelseCounter--;
14038 return "<?php endforeach; if ({$empty}): ?>";
14042 return "<?php while{$expression}: ?>";
14046 return '<?php endwhile; ?>';
14050 return '<?php endfor; ?>';
14054 return '<?php endforeach; ?>';
14058 return '<?php endif; ?>';
14062 return '<?php endif; ?>';
14066 if (starts_with($expression,
'(')) {
14067 $expression = substr($expression, 1, -1);
14069 $data =
"<?php echo \$__env->make({$expression}, array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>";
14070 $this->footer[] = $data;
14075 if (starts_with($expression,
'(')) {
14076 $expression = substr($expression, 1, -1);
14078 return "<?php echo \$__env->make({$expression}, array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>";
14082 return "<?php echo \$__env->yieldContent{$expression}; ?>";
14086 return "<?php \$__env->startSection{$expression}; ?>";
14090 return '<?php $__env->appendSection(); ?>';
14094 $this->extensions[] = $compiler;
14098 return '/(?<!\\w)(\\s*)@' . $function .
'(\\s*\\(.*\\))/';
14102 return '/(?<!\\w)(\\s*)@' . $function .
'(\\s*\\(.*)\\)/';
14106 return '/(?<!\\w)(\\s*)@' . $function .
'(\\s*)/';
14110 $this->rawTags = array(preg_quote($openTag), preg_quote($closeTag));
14114 $property = $escaped ===
true ?
'escapedTags' :
'contentTags';
14115 $this->{$property} = array(preg_quote($openTag), preg_quote($closeTag));
14119 $this->setContentTags($openTag, $closeTag,
true);
14123 return $this->getTags();
14127 return $this->getTags(
true);
14131 $tags = $escaped ? $this->escapedTags : $this->contentTags;
14132 return array_map(
'stripcslashes', $tags);
14136 $this->echoFormat = $format;
14143 const HTTP_CONTINUE = 100;
14144 const HTTP_SWITCHING_PROTOCOLS = 101;
14145 const HTTP_PROCESSING = 102;
14146 const HTTP_OK = 200;
14147 const HTTP_CREATED = 201;
14148 const HTTP_ACCEPTED = 202;
14149 const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
14150 const HTTP_NO_CONTENT = 204;
14151 const HTTP_RESET_CONTENT = 205;
14152 const HTTP_PARTIAL_CONTENT = 206;
14153 const HTTP_MULTI_STATUS = 207;
14154 const HTTP_ALREADY_REPORTED = 208;
14155 const HTTP_IM_USED = 226;
14156 const HTTP_MULTIPLE_CHOICES = 300;
14157 const HTTP_MOVED_PERMANENTLY = 301;
14158 const HTTP_FOUND = 302;
14159 const HTTP_SEE_OTHER = 303;
14160 const HTTP_NOT_MODIFIED = 304;
14161 const HTTP_USE_PROXY = 305;
14162 const HTTP_RESERVED = 306;
14163 const HTTP_TEMPORARY_REDIRECT = 307;
14164 const HTTP_PERMANENTLY_REDIRECT = 308;
14165 const HTTP_BAD_REQUEST = 400;
14166 const HTTP_UNAUTHORIZED = 401;
14167 const HTTP_PAYMENT_REQUIRED = 402;
14168 const HTTP_FORBIDDEN = 403;
14169 const HTTP_NOT_FOUND = 404;
14170 const HTTP_METHOD_NOT_ALLOWED = 405;
14171 const HTTP_NOT_ACCEPTABLE = 406;
14172 const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
14173 const HTTP_REQUEST_TIMEOUT = 408;
14174 const HTTP_CONFLICT = 409;
14175 const HTTP_GONE = 410;
14176 const HTTP_LENGTH_REQUIRED = 411;
14177 const HTTP_PRECONDITION_FAILED = 412;
14178 const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
14179 const HTTP_REQUEST_URI_TOO_LONG = 414;
14180 const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
14181 const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
14182 const HTTP_EXPECTATION_FAILED = 417;
14183 const HTTP_I_AM_A_TEAPOT = 418;
14184 const HTTP_UNPROCESSABLE_ENTITY = 422;
14185 const HTTP_LOCKED = 423;
14186 const HTTP_FAILED_DEPENDENCY = 424;
14187 const HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425;
14188 const HTTP_UPGRADE_REQUIRED = 426;
14189 const HTTP_PRECONDITION_REQUIRED = 428;
14190 const HTTP_TOO_MANY_REQUESTS = 429;
14191 const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
14192 const HTTP_INTERNAL_SERVER_ERROR = 500;
14193 const HTTP_NOT_IMPLEMENTED = 501;
14194 const HTTP_BAD_GATEWAY = 502;
14195 const HTTP_SERVICE_UNAVAILABLE = 503;
14196 const HTTP_GATEWAY_TIMEOUT = 504;
14197 const HTTP_VERSION_NOT_SUPPORTED = 505;
14198 const HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506;
14199 const HTTP_INSUFFICIENT_STORAGE = 507;
14200 const HTTP_LOOP_DETECTED = 508;
14201 const HTTP_NOT_EXTENDED = 510;
14202 const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511;
14209 public static $statusTexts = array(100 =>
'Continue', 101 =>
'Switching Protocols', 102 =>
'Processing', 200 =>
'OK', 201 =>
'Created', 202 =>
'Accepted', 203 =>
'Non-Authoritative Information', 204 =>
'No Content', 205 =>
'Reset Content', 206 =>
'Partial Content', 207 =>
'Multi-Status', 208 =>
'Already Reported', 226 =>
'IM Used', 300 =>
'Multiple Choices', 301 =>
'Moved Permanently', 302 =>
'Found', 303 =>
'See Other', 304 =>
'Not Modified', 305 =>
'Use Proxy', 306 =>
'Reserved', 307 =>
'Temporary Redirect', 308 =>
'Permanent Redirect', 400 =>
'Bad Request', 401 =>
'Unauthorized', 402 =>
'Payment Required', 403 =>
'Forbidden', 404 =>
'Not Found', 405 =>
'Method Not Allowed', 406 =>
'Not Acceptable', 407 =>
'Proxy Authentication Required', 408 =>
'Request Timeout', 409 =>
'Conflict', 410 =>
'Gone', 411 =>
'Length Required', 412 =>
'Precondition Failed', 413 =>
'Request Entity Too Large', 414 =>
'Request-URI Too Long', 415 =>
'Unsupported Media Type', 416 =>
'Requested Range Not Satisfiable', 417 =>
'Expectation Failed', 418 =>
'I\'m a teapot', 422 =>
'Unprocessable Entity', 423 =>
'Locked', 424 =>
'Failed Dependency', 425 =>
'Reserved for WebDAV advanced collections expired proposal', 426 =>
'Upgrade Required', 428 =>
'Precondition Required', 429 =>
'Too Many Requests', 431 =>
'Request Header Fields Too Large', 500 =>
'Internal Server Error', 501 =>
'Not Implemented', 502 =>
'Bad Gateway', 503 =>
'Service Unavailable', 504 =>
'Gateway Timeout', 505 =>
'HTTP Version Not Supported', 506 =>
'Variant Also Negotiates (Experimental)', 507 =>
'Insufficient Storage', 508 =>
'Loop Detected', 510 =>
'Not Extended', 511 =>
'Network Authentication Required');
14210 public function __construct($content =
'', $status = 200, $headers = array())
14213 $this->setContent($content);
14214 $this->setStatusCode($status);
14215 $this->setProtocolVersion(
'1.0');
14216 if (!$this->headers->has(
'Date')) {
14217 $this->setDate(
new \DateTime(null,
new \
DateTimeZone(
'UTC')));
14220 public static function create($content =
'', $status = 200, $headers = array())
14222 return new static($content, $status, $headers);
14226 return sprintf(
'HTTP/%s %s %s', $this->
version, $this->statusCode, $this->statusText) .
'
14227 ' . $this->headers .
'
14228 ' . $this->getContent();
14232 $this->headers = clone $this->headers;
14236 $headers = $this->headers;
14237 if ($this->isInformational() || $this->
isEmpty()) {
14238 $this->setContent(null);
14239 $headers->remove(
'Content-Type');
14240 $headers->remove(
'Content-Length');
14242 if (!$headers->has(
'Content-Type')) {
14244 if (null !== $format && ($mimeType = $request->
getMimeType($format))) {
14245 $headers->set(
'Content-Type', $mimeType);
14248 $charset = $this->charset ?:
'UTF-8';
14249 if (!$headers->has(
'Content-Type')) {
14250 $headers->set(
'Content-Type',
'text/html; charset=' . $charset);
14251 } elseif (0 === stripos($headers->get(
'Content-Type'),
'text/') &&
false === stripos($headers->get(
'Content-Type'),
'charset')) {
14252 $headers->set(
'Content-Type', $headers->get(
'Content-Type') .
'; charset=' . $charset);
14254 if ($headers->has(
'Transfer-Encoding')) {
14255 $headers->remove(
'Content-Length');
14258 $length = $headers->get(
'Content-Length');
14259 $this->setContent(null);
14261 $headers->set(
'Content-Length', $length);
14265 if (
'HTTP/1.0' != $request->server->
get(
'SERVER_PROTOCOL')) {
14266 $this->setProtocolVersion(
'1.1');
14268 if (
'1.0' == $this->getProtocolVersion() &&
'no-cache' == $this->headers->get(
'Cache-Control')) {
14269 $this->headers->set(
'pragma',
'no-cache');
14270 $this->headers->set(
'expires', -1);
14272 $this->ensureIEOverSSLCompatibility($request);
14277 if (headers_sent()) {
14280 header(sprintf(
'HTTP/%s %s %s', $this->
version, $this->statusCode, $this->statusText),
true, $this->statusCode);
14281 foreach ($this->headers->allPreserveCase() as $name => $values) {
14282 foreach ($values as $value) {
14283 header($name .
': ' . $value,
false, $this->statusCode);
14286 foreach ($this->headers->getCookies() as $cookie) {
14287 setcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
14293 echo $this->content;
14298 $this->sendHeaders();
14299 $this->sendContent();
14300 if (function_exists(
'fastcgi_finish_request')) {
14301 fastcgi_finish_request();
14302 } elseif (
'cli' !== PHP_SAPI) {
14303 static::closeOutputBuffers(0,
true);
14309 if (null !== $content && !is_string($content) && !is_numeric($content) && !is_callable(array($content,
'__toString'))) {
14310 throw new \UnexpectedValueException(sprintf(
'The Response content must be a string or object implementing __toString(), "%s" given.', gettype($content)));
14312 $this->content = (string) $content;
14317 return $this->content;
14331 if ($this->isInvalid()) {
14332 throw new \InvalidArgumentException(sprintf(
'The HTTP status code "%s" is not valid.',
$code));
14334 if (null === $text) {
14335 $this->statusText = isset(self::$statusTexts[
$code]) ? self::$statusTexts[
$code] :
'';
14338 if (
false === $text) {
14339 $this->statusText =
'';
14342 $this->statusText = $text;
14347 return $this->statusCode;
14351 $this->charset = $charset;
14356 return $this->charset;
14360 if (!in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) {
14363 if ($this->headers->hasCacheControlDirective(
'no-store') || $this->headers->getCacheControlDirective(
'private')) {
14366 return $this->isValidateable() || $this->isFresh();
14370 return $this->getTtl() > 0;
14374 return $this->headers->has(
'Last-Modified') || $this->headers->has(
'ETag');
14378 $this->headers->removeCacheControlDirective(
'public');
14379 $this->headers->addCacheControlDirective(
'private');
14384 $this->headers->addCacheControlDirective(
'public');
14385 $this->headers->removeCacheControlDirective(
'private');
14390 return $this->headers->hasCacheControlDirective(
'must-revalidate') || $this->headers->has(
'proxy-revalidate');
14394 return $this->headers->getDate(
'Date',
new \DateTime());
14399 $this->headers->set(
'Date', $date->format(
'D, d M Y H:i:s') .
' GMT');
14404 if (null !== ($age = $this->headers->get(
'Age'))) {
14407 return max(time() - $this->getDate()->
format(
'U'), 0);
14411 if ($this->isFresh()) {
14412 $this->headers->set(
'Age', $this->getMaxAge());
14419 return $this->headers->getDate(
'Expires');
14420 }
catch (\RuntimeException $e) {
14421 return \DateTime::createFromFormat(DATE_RFC2822,
'Sat, 01 Jan 00 00:00:00 +0000');
14426 if (null === $date) {
14427 $this->headers->remove(
'Expires');
14429 $date = clone $date;
14431 $this->headers->set(
'Expires', $date->format(
'D, d M Y H:i:s') .
' GMT');
14437 if ($this->headers->hasCacheControlDirective(
's-maxage')) {
14438 return (
int) $this->headers->getCacheControlDirective(
's-maxage');
14440 if ($this->headers->hasCacheControlDirective(
'max-age')) {
14441 return (
int) $this->headers->getCacheControlDirective(
'max-age');
14443 if (null !== $this->getExpires()) {
14444 return $this->getExpires()->format(
'U') - $this->getDate()->format(
'U');
14449 $this->headers->addCacheControlDirective(
'max-age', $value);
14454 $this->setPublic();
14455 $this->headers->addCacheControlDirective(
's-maxage', $value);
14460 if (null !== ($maxAge = $this->getMaxAge())) {
14461 return $maxAge - $this->getAge();
14466 $this->setSharedMaxAge($this->getAge() + $seconds);
14471 $this->setMaxAge($this->getAge() + $seconds);
14476 return $this->headers->getDate(
'Last-Modified');
14480 if (null === $date) {
14481 $this->headers->remove(
'Last-Modified');
14483 $date = clone $date;
14485 $this->headers->set(
'Last-Modified', $date->format(
'D, d M Y H:i:s') .
' GMT');
14491 return $this->headers->get(
'ETag');
14495 if (null === $etag) {
14496 $this->headers->remove(
'Etag');
14498 if (0 !== strpos($etag,
'"')) {
14499 $etag =
'"' . $etag .
'"';
14501 $this->headers->set(
'ETag', (
true === $weak ?
'W/' :
'') . $etag);
14507 if (
$diff = array_diff(array_keys($options), array(
'etag',
'last_modified',
'max_age',
's_maxage',
'private',
'public'))) {
14508 throw new \InvalidArgumentException(sprintf(
'Response does not support the following options: "%s".', implode(
'", "', array_values(
$diff))));
14510 if (isset($options[
'etag'])) {
14511 $this->setEtag($options[
'etag']);
14513 if (isset($options[
'last_modified'])) {
14514 $this->setLastModified($options[
'last_modified']);
14516 if (isset($options[
'max_age'])) {
14517 $this->setMaxAge($options[
'max_age']);
14519 if (isset($options[
's_maxage'])) {
14520 $this->setSharedMaxAge($options[
's_maxage']);
14522 if (isset($options[
'public'])) {
14523 if ($options[
'public']) {
14524 $this->setPublic();
14526 $this->setPrivate();
14529 if (isset($options[
'private'])) {
14530 if ($options[
'private']) {
14531 $this->setPrivate();
14533 $this->setPublic();
14540 $this->setStatusCode(304);
14541 $this->setContent(null);
14542 foreach (array(
'Allow',
'Content-Encoding',
'Content-Language',
'Content-Length',
'Content-MD5',
'Content-Type',
'Last-Modified') as $header) {
14543 $this->headers->remove($header);
14549 return null !== $this->headers->get(
'Vary');
14553 if (!($vary = $this->headers->get(
'Vary', null,
false))) {
14557 foreach ($vary as $item) {
14558 $ret = array_merge($ret, preg_split(
'/[\\s,]+/', $item));
14564 $this->headers->set(
'Vary', $headers, $replace);
14572 $notModified =
false;
14573 $lastModified = $this->headers->get(
'Last-Modified');
14574 $modifiedSince = $request->headers->
get(
'If-Modified-Since');
14575 if ($etags = $request->getEtags()) {
14576 $notModified = in_array($this->getEtag(), $etags) || in_array(
'*', $etags);
14578 if ($modifiedSince && $lastModified) {
14579 $notModified = strtotime($modifiedSince) >= strtotime($lastModified) && (!$etags || $notModified);
14581 if ($notModified) {
14582 $this->setNotModified();
14584 return $notModified;
14588 return $this->statusCode < 100 || $this->statusCode >= 600;
14592 return $this->statusCode >= 100 && $this->statusCode < 200;
14596 return $this->statusCode >= 200 && $this->statusCode < 300;
14600 return $this->statusCode >= 300 && $this->statusCode < 400;
14604 return $this->statusCode >= 400 && $this->statusCode < 500;
14608 return $this->statusCode >= 500 && $this->statusCode < 600;
14612 return 200 === $this->statusCode;
14616 return 403 === $this->statusCode;
14620 return 404 === $this->statusCode;
14624 return in_array($this->statusCode, array(201, 301, 302, 303, 307, 308)) && (null === $location ?: $location == $this->headers->get(
'Location'));
14628 return in_array($this->statusCode, array(204, 304));
14632 $status = ob_get_status(
true);
14633 $level = count($status);
14634 while ($level-- > $targetLevel && (!
empty($status[$level][
'del']) || isset($status[$level][
'flags']) && $status[$level][
'flags'] & PHP_OUTPUT_HANDLER_REMOVABLE && $status[$level][
'flags'] & ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE))) {
14644 if (
false !== stripos($this->headers->get(
'Content-Disposition'),
'attachment') && preg_match(
'/MSIE (.*?);/i', $request->server->
get(
'HTTP_USER_AGENT'), $match) == 1 &&
true === $request->
isSecure()) {
14645 if ((
int) preg_replace(
'/(MSIE )(.*?);/',
'$2', $match[0]) < 9) {
14646 $this->headers->remove(
'Cache-Control');
14656 public function header($key, $value, $replace =
true)
14658 $this->headers->set($key, $value, $replace);
14661 public function withCookie(
Cookie $cookie)
14663 $this->headers->setCookie($cookie);
14679 $this->original = $content;
14680 if ($this->shouldBeJson($content)) {
14681 $this->headers->set(
'Content-Type',
'application/json');
14682 $content = $this->morphToJson($content);
14684 $content = $content->render();
14686 return parent::setContent($content);
14690 if ($content instanceof
Jsonable) {
14691 return $content->toJson();
14693 return json_encode($content);
14697 return $content instanceof
Jsonable || $content instanceof ArrayObject || is_array($content);
14701 return $this->original;
14708 const COOKIES_FLAT =
'flat';
14709 const COOKIES_ARRAY =
'array';
14710 const DISPOSITION_ATTACHMENT =
'attachment';
14711 const DISPOSITION_INLINE =
'inline';
14712 protected $computedCacheControl = array();
14713 protected $cookies = array();
14714 protected $headerNames = array();
14717 parent::__construct($headers);
14718 if (!isset($this->headers[
'cache-control'])) {
14719 $this->
set(
'Cache-Control',
'');
14725 foreach ($this->getCookies() as $cookie) {
14726 $cookies .=
'Set-Cookie: ' . $cookie .
'
14729 ksort($this->headerNames);
14730 return parent::__toString() . $cookies;
14734 return array_combine($this->headerNames, $this->headers);
14738 $this->headerNames = array();
14739 parent::replace($headers);
14740 if (!isset($this->headers[
'cache-control'])) {
14741 $this->
set(
'Cache-Control',
'');
14744 public function set($key, $values, $replace =
true)
14747 $uniqueKey = strtr(strtolower($key),
'_',
'-');
14748 $this->headerNames[$uniqueKey] = $key;
14749 if (in_array($uniqueKey, array(
'cache-control',
'etag',
'last-modified',
'expires'))) {
14750 $computed = $this->computeCacheControlValue();
14751 $this->headers[
'cache-control'] = array($computed);
14752 $this->headerNames[
'cache-control'] =
'Cache-Control';
14753 $this->computedCacheControl = $this->parseCacheControl($computed);
14756 public function remove($key)
14759 $uniqueKey = strtr(strtolower($key),
'_',
'-');
14760 unset($this->headerNames[$uniqueKey]);
14761 if (
'cache-control' === $uniqueKey) {
14762 $this->computedCacheControl = array();
14767 return array_key_exists($key, $this->computedCacheControl);
14771 return array_key_exists($key, $this->computedCacheControl) ? $this->computedCacheControl[$key] : null;
14779 if (null ===
$path) {
14782 unset($this->cookies[$domain][
$path][$name]);
14783 if (
empty($this->cookies[$domain][
$path])) {
14784 unset($this->cookies[$domain][$path]);
14785 if (
empty($this->cookies[$domain])) {
14786 unset($this->cookies[$domain]);
14792 if (!in_array($format, array(self::COOKIES_FLAT, self::COOKIES_ARRAY))) {
14793 throw new \InvalidArgumentException(sprintf(
'Format "%s" invalid (%s).', $format, implode(
', ', array(self::COOKIES_FLAT, self::COOKIES_ARRAY))));
14795 if (self::COOKIES_ARRAY === $format) {
14796 return $this->cookies;
14798 $flattenedCookies = array();
14799 foreach ($this->cookies as
$path) {
14800 foreach ($path as $cookies) {
14801 foreach ($cookies as $cookie) {
14802 $flattenedCookies[] = $cookie;
14806 return $flattenedCookies;
14810 $this->setCookie(
new Cookie($name, null, 1,
$path, $domain, $secure, $httpOnly));
14814 if (!in_array($disposition, array(self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE))) {
14815 throw new \InvalidArgumentException(sprintf(
'The disposition must be either "%s" or "%s".', self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE));
14817 if (
'' == $filenameFallback) {
14818 $filenameFallback = $filename;
14820 if (!preg_match(
'/^[\\x20-\\x7e]*$/', $filenameFallback)) {
14821 throw new \InvalidArgumentException(
'The filename fallback must only contain ASCII characters.');
14823 if (
false !== strpos($filenameFallback,
'%')) {
14824 throw new \InvalidArgumentException(
'The filename fallback cannot contain the "%" character.');
14826 if (
false !== strpos($filename,
'/') ||
false !== strpos($filename,
'\\') ||
false !== strpos($filenameFallback,
'/') ||
false !== strpos($filenameFallback,
'\\')) {
14827 throw new \InvalidArgumentException(
'The filename and the fallback cannot contain the "/" and "\\" characters.');
14829 $output = sprintf(
'%s; filename="%s"', $disposition, str_replace(
'"',
'\\"', $filenameFallback));
14830 if ($filename !== $filenameFallback) {
14831 $output .= sprintf(
'; filename*=utf-8\'\'%s', rawurlencode($filename));
14837 if (!$this->cacheControl && !$this->has(
'ETag') && !$this->has(
'Last-Modified') && !$this->has(
'Expires')) {
14840 if (!$this->cacheControl) {
14841 return 'private, must-revalidate';
14843 $header = $this->getCacheControlHeader();
14844 if (isset($this->cacheControl[
'public']) || isset($this->cacheControl[
'private'])) {
14847 if (!isset($this->cacheControl[
's-maxage'])) {
14848 return $header .
', private';
14864 public function __construct($name, $value = null, $expire = 0,
$path =
'/', $domain = null, $secure =
false, $httpOnly =
true)
14866 if (preg_match(
'/[=,;
14868 throw new \InvalidArgumentException(sprintf(
'The cookie name "%s" contains invalid characters.', $name));
14870 if (
empty($name)) {
14871 throw new \InvalidArgumentException(
'The cookie name cannot be empty.');
14873 if ($expire instanceof \DateTime) {
14874 $expire = $expire->format(
'U');
14875 } elseif (!is_numeric($expire)) {
14876 $expire = strtotime($expire);
14877 if (
false === $expire || -1 === $expire) {
14878 throw new \InvalidArgumentException(
'The cookie expiration time is not valid.');
14881 $this->
name = $name;
14882 $this->value = $value;
14883 $this->domain = $domain;
14884 $this->expire = $expire;
14886 $this->secure = (bool) $secure;
14887 $this->httpOnly = (bool) $httpOnly;
14891 $str = urlencode($this->getName()) .
'=';
14892 if (
'' === (
string) $this->getValue()) {
14893 $str .=
'deleted; expires=' . gmdate(
'D, d-M-Y H:i:s T', time() - 31536001);
14895 $str .= urlencode($this->getValue());
14896 if ($this->getExpiresTime() !== 0) {
14897 $str .=
'; expires=' . gmdate(
'D, d-M-Y H:i:s T', $this->getExpiresTime());
14903 if ($this->getDomain()) {
14904 $str .=
'; domain=' . $this->getDomain();
14906 if (
true === $this->isSecure()) {
14907 $str .=
'; secure';
14909 if (
true === $this->isHttpOnly()) {
14910 $str .=
'; httponly';
14916 return $this->name;
14920 return $this->value;
14924 return $this->domain;
14928 return $this->expire;
14936 return $this->secure;
14940 return $this->httpOnly;
14944 return $this->expire < time();
14951 private function __construct()
14954 public static function equals($knownString, $userInput)
14956 if (!is_string($knownString)) {
14957 $knownString = (string) $knownString;
14959 if (!is_string($userInput)) {
14960 $userInput = (string) $userInput;
14962 if (function_exists(
'hash_equals')) {
14963 return hash_equals($knownString, $userInput);
14965 $knownLen = self::safeStrlen($knownString);
14966 $userLen = self::safeStrlen($userInput);
14967 if ($userLen !== $knownLen) {
14971 for (
$i = 0;
$i < $knownLen;
$i++) {
14972 $result |= ord($knownString[
$i]) ^ ord($userInput[$i]);
14974 return 0 === $result;
14978 static $funcExists = null;
14979 if (null === $funcExists) {
14980 $funcExists = function_exists(
'mb_strlen');
14983 return mb_strlen($string,
'8bit');
14985 return strlen($string);
14992 public function nextBytes($nbBytes);
15000 private $useOpenSsl;
15002 private $seedUpdated;
15003 private $seedLastUpdatedAt;
15007 $this->seedFile = $seedFile;
15008 $this->logger = $logger;
15009 if (
'\\' === DIRECTORY_SEPARATOR && PHP_VERSION_ID < 50304) {
15010 $this->useOpenSsl =
false;
15011 } elseif (!function_exists(
'openssl_random_pseudo_bytes')) {
15012 if (null !== $this->logger) {
15013 $this->logger->notice(
'It is recommended that you enable the "openssl" extension for random number generation.');
15015 $this->useOpenSsl =
false;
15017 $this->useOpenSsl =
true;
15022 if ($this->useOpenSsl) {
15023 $bytes = openssl_random_pseudo_bytes($nbBytes, $strong);
15024 if (
false !== $bytes &&
true === $strong) {
15027 if (null !== $this->logger) {
15028 $this->logger->info(
'OpenSSL did not produce a secure random number.');
15031 if (null === $this->
seed) {
15032 if (null === $this->seedFile) {
15033 throw new \RuntimeException(
'You need to specify a file path to store the seed.');
15035 if (is_file($this->seedFile)) {
15036 list($this->
seed, $this->seedLastUpdatedAt) = $this->readSeed();
15038 $this->
seed = uniqid(mt_rand(),
true);
15039 $this->updateSeed();
15043 while (strlen($bytes) < $nbBytes) {
15045 $bytes .= hash(
'sha512', $incr++ . $this->
seed . uniqid(mt_rand(),
true) . $nbBytes,
true);
15046 $this->
seed = base64_encode(hash(
'sha512', $this->
seed . $bytes . $nbBytes,
true));
15047 $this->updateSeed();
15049 return substr($bytes, 0, $nbBytes);
15051 private function readSeed()
15053 return json_decode(file_get_contents($this->seedFile));
15055 private function updateSeed()
15057 if (!$this->seedUpdated && $this->seedLastUpdatedAt < time() - mt_rand(1, 10)) {
15058 file_put_contents($this->seedFile, json_encode(array($this->
seed, microtime(
true))));
15060 $this->seedUpdated =
true;
15067 private $relativePath;
15068 private $relativePathname;
15071 parent::__construct($file);
15072 $this->relativePath = $relativePath;
15073 $this->relativePathname = $relativePathname;
15077 return $this->relativePath;
15081 return $this->relativePathname;
15085 $level = error_reporting(0);
15086 $content = file_get_contents($this->getPathname());
15087 error_reporting($level);
15088 if (
false === $content) {
15089 $error = error_get_last();
15090 throw new \RuntimeException($error[
'message']);
15099 const START_FLAG =
'^';
15100 const END_FLAG =
'$';
15101 const BOUNDARY =
'~';
15102 const JOKER =
'.*';
15103 const ESCAPING =
'\\';
15106 private $startFlag;
15108 private $startJoker;
15112 if (preg_match(
'/^(.{3,}?)([imsxuADU]*)$/', $expr, $m)) {
15113 $start = substr($m[1], 0, 1);
15114 $end = substr($m[1], -1);
15115 if (
$start === $end && !preg_match(
'/[*?[:alnum:] \\\\]/',
$start) ||
$start ===
'{' && $end ===
'}' ||
$start ===
'(' && $end ===
')') {
15116 return new self(substr($m[1], 1, -1), $m[2], $end);
15119 throw new \InvalidArgumentException(
'Given expression is not a regex.');
15123 if (null !== $delimiter) {
15124 $pattern = str_replace(
'\\' . $delimiter, $delimiter, $pattern);
15126 $this->parsePattern($pattern);
15135 return self::BOUNDARY . $this->renderPattern() . self::BOUNDARY .
$this->options;
15139 return ($this->startFlag ? self::START_FLAG :
'') . ($this->startJoker ? self::JOKER :
'') . str_replace(self::BOUNDARY,
'\\' . self::BOUNDARY, $this->pattern) . ($this->endJoker ? self::JOKER :
'') . ($this->endFlag ? self::END_FLAG :
'');
15143 return !$this->hasOption(
'i');
15147 return Expression::TYPE_REGEX;
15151 $this->pattern = $expr . $this->pattern;
15156 $this->pattern .= $expr;
15161 return false !== strpos($this->
options, $option);
15165 if (!$this->hasOption($option)) {
15177 $this->startFlag = $startFlag;
15182 return $this->startFlag;
15186 $this->endFlag = (bool) $endFlag;
15191 return $this->endFlag;
15195 $this->startJoker = $startJoker;
15200 return $this->startJoker;
15204 $this->endJoker = (bool) $endJoker;
15209 return $this->endJoker;
15213 $replace =
function ($subject) use($replacement) {
15214 $subject = $subject[0];
15215 $replace = 0 === substr_count($subject,
'\\') % 2;
15216 return $replace ? str_replace(
'.', $replacement, $subject) : $subject;
15218 $this->pattern = preg_replace_callback(
'~[\\\\]*\\.~', $replace, $this->pattern);
15221 private function parsePattern($pattern)
15223 if ($this->startFlag = self::START_FLAG === substr($pattern, 0, 1)) {
15224 $pattern = substr($pattern, 1);
15226 if ($this->startJoker = self::JOKER === substr($pattern, 0, 2)) {
15227 $pattern = substr($pattern, 2);
15229 if ($this->endFlag = self::END_FLAG === substr($pattern, -1) && self::ESCAPING !== substr($pattern, -2, -1)) {
15230 $pattern = substr($pattern, 0, -1);
15232 if ($this->endJoker = self::JOKER === substr($pattern, -2) && self::ESCAPING !== substr($pattern, -3, -2)) {
15233 $pattern = substr($pattern, 0, -2);
15235 $this->pattern = $pattern;
15242 public function render();
15243 public function renderPattern();
15244 public function isCaseSensitive();
15245 public function getType();
15246 public function prepend($expr);
15247 public function append($expr);
15253 const TYPE_REGEX = 1;
15254 const TYPE_GLOB = 2;
15258 return new self($expr);
15263 $this->value = Regex::create($expr);
15264 }
catch (\InvalidArgumentException $e) {
15265 $this->value =
new Glob($expr);
15274 return $this->value->render();
15278 return $this->value->renderPattern();
15282 return $this->value->isCaseSensitive();
15286 return $this->value->getType();
15290 $this->value->prepend($expr);
15295 $this->value->append($expr);
15300 return self::TYPE_REGEX === $this->value->getType();
15304 return self::TYPE_GLOB === $this->value->getType();
15308 if (self::TYPE_GLOB !== $this->value->getType()) {
15309 throw new \LogicException(
'Regex can\'t be transformed to glob.');
15311 return $this->value;
15315 return self::TYPE_REGEX === $this->value->getType() ? $this->value : $this->value->toRegex();
15325 while ($iterator instanceof \OuterIterator) {
15326 $innerIterator = $iterator->getInnerIterator();
15328 if ($innerIterator->isRewindable()) {
15329 $innerIterator->next();
15330 $innerIterator->rewind();
15332 } elseif ($iterator->getInnerIterator() instanceof \FilesystemIterator) {
15333 $iterator->getInnerIterator()->next();
15334 $iterator->getInnerIterator()->rewind();
15336 $iterator = $iterator->getInnerIterator();
15346 protected $matchRegexps = array();
15347 protected $noMatchRegexps = array();
15348 public function __construct(\Iterator $iterator, array $matchPatterns, array $noMatchPatterns)
15350 foreach ($matchPatterns as $pattern) {
15351 $this->matchRegexps[] = $this->toRegex($pattern);
15353 foreach ($noMatchPatterns as $pattern) {
15354 $this->noMatchRegexps[] = $this->toRegex($pattern);
15356 parent::__construct($iterator);
15360 return Expression::create($str)->isRegex();
15362 protected abstract function toRegex($str);
15370 $filename = $this->current()->getRelativePathname();
15371 if (
'\\' === DIRECTORY_SEPARATOR) {
15372 $filename = strtr($filename,
'\\',
'/');
15374 foreach ($this->noMatchRegexps as $regex) {
15375 if (preg_match($regex, $filename)) {
15380 if ($this->matchRegexps) {
15382 foreach ($this->matchRegexps as $regex) {
15383 if (preg_match($regex, $filename)) {
15392 return $this->isRegex($str) ? $str :
'/' . preg_quote($str,
'/') .
'/';
15399 private $patterns = array();
15402 foreach ($directories as $directory) {
15403 $this->patterns[] =
'#(^|/)' . preg_quote($directory,
'#') .
'(/|$)#';
15405 parent::__construct($iterator);
15409 $path = $this->isDir() ? $this->current()->getRelativePathname() : $this->current()->getRelativePath();
15411 foreach ($this->patterns as $pattern) {
15412 if (preg_match($pattern,
$path)) {
15425 private $ignoreUnreadableDirs;
15426 private $rewindable;
15429 if ($flags & (self::CURRENT_AS_PATHNAME | self::CURRENT_AS_SELF)) {
15430 throw new \RuntimeException(
'This iterator only support returning current as fileinfo.');
15432 parent::__construct(
$path, $flags);
15433 $this->ignoreUnreadableDirs = $ignoreUnreadableDirs;
15437 return new SplFileInfo(parent::current()->getPathname(), $this->getSubPath(), $this->getSubPathname());
15442 $children = parent::getChildren();
15443 if ($children instanceof
self) {
15444 $children->ignoreUnreadableDirs = $this->ignoreUnreadableDirs;
15448 if ($this->ignoreUnreadableDirs) {
15449 return new \RecursiveArrayIterator(array());
15457 if (
false === $this->isRewindable()) {
15465 if (null !== $this->rewindable) {
15466 return $this->rewindable;
15468 if (
false !== ($stream = @opendir($this->getPath()))) {
15469 $infos = stream_get_meta_data($stream);
15471 if ($infos[
'seekable']) {
15472 return $this->rewindable =
true;
15475 return $this->rewindable =
false;
15482 const ONLY_FILES = 1;
15483 const ONLY_DIRECTORIES = 2;
15487 $this->mode = $mode;
15488 parent::__construct($iterator);
15492 $fileinfo = $this->current();
15493 if (self::ONLY_DIRECTORIES === (self::ONLY_DIRECTORIES & $this->mode) && $fileinfo->isFile()) {
15495 } elseif (self::ONLY_FILES === (self::ONLY_FILES & $this->mode) && $fileinfo->isDir()) {
15505 const TYPE_UNIX = 1;
15506 const TYPE_DARWIN = 2;
15507 const TYPE_CYGWIN = 3;
15508 const TYPE_WINDOWS = 4;
15509 const TYPE_BSD = 5;
15513 if (null === $this->type) {
15514 $this->type = $this->guessType();
15516 return $this->type;
15520 if (!function_exists(
'exec')) {
15523 $testCommand =
'which ';
15524 if (self::TYPE_WINDOWS === $this->type) {
15525 $testCommand =
'where ';
15527 $command = escapeshellcmd($command);
15531 private function guessType()
15533 $os = strtolower(PHP_OS);
15534 if (
false !== strpos($os,
'cygwin')) {
15535 return self::TYPE_CYGWIN;
15537 if (
false !== strpos($os,
'darwin')) {
15538 return self::TYPE_DARWIN;
15540 if (
false !== strpos($os,
'bsd')) {
15541 return self::TYPE_BSD;
15543 if (0 === strpos($os,
'win')) {
15544 return self::TYPE_WINDOWS;
15546 return self::TYPE_UNIX;
15553 public function setFollowLinks($followLinks);
15554 public function setMode($mode);
15555 public function setExclude(array $exclude);
15556 public function setDepths(array $depths);
15557 public function setNames(array $names);
15558 public function setNotNames(array $notNames);
15559 public function setContains(array $contains);
15560 public function setNotContains(array $notContains);
15561 public function setSizes(array $sizes);
15562 public function setDates(array $dates);
15563 public function setFilters(array $filters);
15564 public function setSort($sort);
15565 public function setPath(array $paths);
15566 public function setNotPath(array $notPaths);
15567 public function ignoreUnreadableDirs($ignore =
true);
15568 public function searchInDirectory($dir);
15569 public function isSupported();
15570 public function getName();
15576 protected $followLinks =
false;
15577 protected $mode = 0;
15578 protected $minDepth = 0;
15579 protected $maxDepth = PHP_INT_MAX;
15580 protected $exclude = array();
15581 protected $names = array();
15582 protected $notNames = array();
15583 protected $contains = array();
15584 protected $notContains = array();
15585 protected $sizes = array();
15586 protected $dates = array();
15587 protected $filters = array();
15588 protected $sort =
false;
15589 protected $paths = array();
15590 protected $notPaths = array();
15591 protected $ignoreUnreadableDirs =
false;
15592 private static $areSupported = array();
15595 $name = $this->getName();
15596 if (!array_key_exists($name, self::$areSupported)) {
15597 self::$areSupported[$name] = $this->canBeUsed();
15599 return self::$areSupported[$name];
15603 $this->followLinks = $followLinks;
15608 $this->mode = $mode;
15613 $this->minDepth = 0;
15614 $this->maxDepth = PHP_INT_MAX;
15615 foreach ($depths as $comparator) {
15616 switch ($comparator->getOperator()) {
15618 $this->minDepth = $comparator->getTarget() + 1;
15621 $this->minDepth = $comparator->getTarget();
15624 $this->maxDepth = $comparator->getTarget() - 1;
15627 $this->maxDepth = $comparator->getTarget();
15630 $this->minDepth = $this->maxDepth = $comparator->getTarget();
15637 $this->exclude = $exclude;
15642 $this->names = $names;
15647 $this->notNames = $notNames;
15657 $this->notContains = $notContains;
15662 $this->sizes = $sizes;
15667 $this->dates = $dates;
15672 $this->filters = $filters;
15677 $this->
sort = $sort;
15682 $this->paths = $paths;
15687 $this->notPaths = $notPaths;
15692 $this->ignoreUnreadableDirs = (bool) $ignore;
15695 protected abstract function canBeUsed();
15711 $this->shell =
new Shell();
15715 $dir = realpath($dir);
15716 if (Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES === $this->mode && ($this->
contains || $this->notContains)) {
15719 $command = Command::create();
15720 $find = $this->buildFindCommand($command, $dir);
15721 if ($this->followLinks) {
15722 $find->add(
'-follow');
15724 $find->add(
'-mindepth')->add($this->minDepth + 1);
15725 if (PHP_INT_MAX !== $this->maxDepth) {
15726 $find->add(
'-maxdepth')->add($this->maxDepth + 1);
15728 if (Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES === $this->mode) {
15729 $find->add(
'-type d');
15730 } elseif (Iterator\FileTypeFilterIterator::ONLY_FILES === $this->mode) {
15731 $find->add(
'-type f');
15733 $this->buildNamesFiltering($find, $this->names);
15734 $this->buildNamesFiltering($find, $this->notNames,
true);
15735 $this->buildPathsFiltering($find, $dir, $this->paths);
15736 $this->buildPathsFiltering($find, $dir, $this->notPaths,
true);
15737 $this->buildSizesFiltering($find, $this->sizes);
15738 $this->buildDatesFiltering($find, $this->dates);
15739 $useGrep = $this->shell->testCommand(
'grep') && $this->shell->testCommand(
'xargs');
15740 $useSort = is_int($this->
sort) && $this->shell->testCommand(
'sort') && $this->shell->testCommand(
'cut');
15741 if ($useGrep && ($this->
contains || $this->notContains)) {
15742 $grep = $command->ins(
'grep');
15743 $this->buildContentFiltering($grep, $this->
contains);
15744 $this->buildContentFiltering($grep, $this->notContains,
true);
15747 $this->buildSorting($command, $this->
sort);
15749 $command->setErrorHandler($this->ignoreUnreadableDirs ?
function ($stderr) {
15751 } :
function ($stderr) {
15754 $paths = $this->shell->testCommand(
'uniq') ? $command->add(
'| uniq')->execute() : array_unique($command->execute());
15756 if ($this->exclude) {
15759 if (!$useGrep && ($this->
contains || $this->notContains)) {
15762 if ($this->filters) {
15765 if (!$useSort && $this->
sort) {
15767 $iterator = $iteratorAggregate->getIterator();
15773 return $this->shell->testCommand(
'find');
15777 return $command->
ins(
'find')->add(
'find ')->arg($dir)->add(
'-noleaf');
15779 private function buildNamesFiltering(
Command $command, array $names, $not =
false)
15781 if (0 === count($names)) {
15784 $command->
add($not ?
'-not' : null)->cmd(
'(');
15785 foreach ($names as
$i => $name) {
15786 $expr = Expression::create($name);
15787 if ($expr->isGlob() && $expr->getGlob()->isExpandable()) {
15788 $expr = Expression::create($expr->getGlob()->toRegex(
false));
15790 if ($expr->isRegex()) {
15791 $regex = $expr->getRegex();
15792 $regex->prepend($regex->hasStartFlag() ?
'/' :
'/[^/]*')->setStartFlag(
false)->setStartJoker(
true)->replaceJokers(
'[^/]');
15793 if (!$regex->hasEndFlag() || $regex->hasEndJoker()) {
15794 $regex->setEndJoker(
false)->append(
'[^/]*');
15797 $command->
add(
$i > 0 ?
'-or' : null)->add($expr->isRegex() ? $expr->isCaseSensitive() ?
'-regex' :
'-iregex' : ($expr->isCaseSensitive() ?
'-name' :
'-iname'))->arg($expr->renderPattern());
15799 $command->
cmd(
')');
15801 private function buildPathsFiltering(Command $command, $dir, array $paths, $not =
false)
15803 if (0 === count($paths)) {
15806 $command->add($not ?
'-not' : null)->cmd(
'(');
15807 foreach ($paths as
$i =>
$path) {
15808 $expr = Expression::create(
$path);
15809 if ($expr->isGlob() && $expr->getGlob()->isExpandable()) {
15810 $expr = Expression::create($expr->getGlob()->toRegex(
false));
15812 if ($expr->isRegex()) {
15813 $regex = $expr->getRegex();
15814 $regex->prepend($regex->hasStartFlag() ? preg_quote($dir) . DIRECTORY_SEPARATOR :
'.*')->setEndJoker(!$regex->hasEndFlag());
15816 $expr->prepend(
'*')->append(
'*');
15818 $command->add(
$i > 0 ?
'-or' : null)->add($expr->isRegex() ? $expr->isCaseSensitive() ?
'-regex' :
'-iregex' : ($expr->isCaseSensitive() ?
'-path' :
'-ipath'))->arg($expr->renderPattern());
15820 $command->cmd(
')');
15822 private function buildSizesFiltering(Command $command, array $sizes)
15824 foreach ($sizes as
$i => $size) {
15825 $command->add(
$i > 0 ?
'-and' : null);
15826 switch ($size->getOperator()) {
15828 $command->add(
'-size -' . ($size->getTarget() + 1) .
'c');
15831 $command->add(
'-size +' . ($size->getTarget() - 1) .
'c');
15834 $command->add(
'-size +' . $size->getTarget() .
'c');
15837 $command->add(
'-size -' . $size->getTarget() .
'c');
15838 $command->add(
'-size +' . $size->getTarget() .
'c');
15842 $command->add(
'-size -' . $size->getTarget() .
'c');
15846 private function buildDatesFiltering(Command $command, array $dates)
15848 foreach ($dates as
$i => $date) {
15849 $command->add(
$i > 0 ?
'-and' : null);
15850 $mins = (int)
round((time() - $date->getTarget()) / 60);
15852 $command->add(
' -mmin -0');
15855 switch ($date->getOperator()) {
15857 $command->add(
'-mmin +' . ($mins - 1));
15860 $command->add(
'-mmin -' . ($mins + 1));
15863 $command->add(
'-mmin -' . $mins);
15866 $command->add(
'-mmin +' . $mins .
' -or -mmin -' . $mins);
15870 $command->add(
'-mmin +' . $mins);
15874 private function buildSorting(Command $command, $sort)
15876 $this->buildFormatSorting($command, $sort);
15878 protected abstract function buildFormatSorting(Command $command, $sort);
15879 protected abstract function buildContentFiltering(Command $command, array $contains, $not =
false);
15896 case SortableIterator::SORT_BY_NAME:
15897 $command->
ins(
'sort')->add(
'| sort');
15899 case SortableIterator::SORT_BY_TYPE:
15902 case SortableIterator::SORT_BY_ACCESSED_TIME:
15905 case SortableIterator::SORT_BY_CHANGED_TIME:
15908 case SortableIterator::SORT_BY_MODIFIED_TIME:
15912 throw new \InvalidArgumentException(sprintf(
'Unknown sort options: %s.', $sort));
15914 $command->
get(
'find')->add(
'-printf')->arg($format .
' %h/%f\\n')->add(
'| sort | cut')->arg(
'-d ')->arg(
'-f2-');
15918 return $this->shell->getType() === Shell::TYPE_UNIX && parent::canBeUsed();
15922 return parent::buildFindCommand($command, $dir)->add(
'-regextype posix-extended');
15926 foreach ($contains as $contain) {
15927 $expr = Expression::create($contain);
15928 $command->
add(
'| xargs -I{} -r grep -I')->add($expr->isCaseSensitive() ? null :
'-i')->add($not ?
'-L' :
'-l')->add(
'-Ee')->arg($expr->renderPattern())->add(
'{}');
15939 $flags = \RecursiveDirectoryIterator::SKIP_DOTS;
15940 if ($this->followLinks) {
15941 $flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
15943 $iterator = new \RecursiveIteratorIterator(
new Iterator\
RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs), \RecursiveIteratorIterator::SELF_FIRST);
15944 if ($this->minDepth > 0 || $this->maxDepth < PHP_INT_MAX) {
15950 if ($this->exclude) {
15953 if ($this->names || $this->notNames) {
15956 if ($this->
contains || $this->notContains) {
15959 if ($this->sizes) {
15962 if ($this->dates) {
15965 if ($this->filters) {
15970 $iterator = $iteratorAggregate->getIterator();
15972 if ($this->paths || $this->notPaths) {
16000 return in_array($this->shell->getType(), array(Shell::TYPE_BSD, Shell::TYPE_DARWIN)) && parent::canBeUsed();
16005 case SortableIterator::SORT_BY_NAME:
16006 $command->
ins(
'sort')->add(
'| sort');
16008 case SortableIterator::SORT_BY_TYPE:
16011 case SortableIterator::SORT_BY_ACCESSED_TIME:
16014 case SortableIterator::SORT_BY_CHANGED_TIME:
16017 case SortableIterator::SORT_BY_MODIFIED_TIME:
16021 throw new \InvalidArgumentException(sprintf(
'Unknown sort options: %s.', $sort));
16023 $command->
add(
'-print0 | xargs -0 stat -f')->arg($format .
'%t%N')->add(
'| sort | cut -f 2');
16027 parent::buildFindCommand($command, $dir)->addAtIndex(
'-E', 1);
16032 foreach ($contains as $contain) {
16033 $expr = Expression::create($contain);
16034 $command->
add(
'| grep -v \'^$\'')->add(
'| xargs -I{} grep -I')->add($expr->isCaseSensitive() ? null :
'-i')->add($not ?
'-L' :
'-l')->add(
'-Ee')->arg($expr->renderPattern())->add(
'{}');
16055 class Finder implements \IteratorAggregate, \Countable
16057 const IGNORE_VCS_FILES = 1;
16058 const IGNORE_DOT_FILES = 2;
16060 private $names = array();
16061 private $notNames = array();
16062 private $exclude = array();
16063 private $filters = array();
16064 private $depths = array();
16065 private $sizes = array();
16066 private $followLinks =
false;
16067 private $sort =
false;
16068 private $ignore = 0;
16069 private $dirs = array();
16070 private $dates = array();
16071 private $iterators = array();
16072 private $contains = array();
16073 private $notContains = array();
16074 private $adapters = array();
16075 private $paths = array();
16076 private $notPaths = array();
16077 private $ignoreUnreadableDirs =
false;
16078 private static $vcsPatterns = array(
'.svn',
'_svn',
'CVS',
'_darcs',
'.arch-params',
'.monotone',
'.bzr',
'.git',
'.hg');
16081 $this->ignore = static::IGNORE_VCS_FILES | static::IGNORE_DOT_FILES;
16086 return new static();
16090 $this->adapters[$adapter->
getName()] = array(
'adapter' => $adapter,
'priority' => $priority,
'selected' =>
false);
16091 return $this->sortAdapters();
16095 $this->resetAdapterSelection();
16096 return $this->sortAdapters();
16100 if (!isset($this->adapters[$name])) {
16101 throw new \InvalidArgumentException(sprintf(
'Adapter "%s" does not exist.', $name));
16103 $this->resetAdapterSelection();
16104 $this->adapters[$name][
'selected'] =
true;
16105 return $this->sortAdapters();
16109 $this->adapters = array();
16114 return array_values(array_map(
function (array $adapter) {
16115 return $adapter[
'adapter'];
16116 }, $this->adapters));
16120 $this->mode = Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES;
16125 $this->mode = Iterator\FileTypeFilterIterator::ONLY_FILES;
16140 $this->names[] = $pattern;
16145 $this->notNames[] = $pattern;
16155 $this->notContains[] = $pattern;
16160 $this->paths[] = $pattern;
16165 $this->notPaths[] = $pattern;
16175 $this->exclude = array_merge($this->exclude, (array) $dirs);
16180 if ($ignoreDotFiles) {
16181 $this->ignore |= static::IGNORE_DOT_FILES;
16183 $this->ignore &= ~static::IGNORE_DOT_FILES;
16190 $this->ignore |= static::IGNORE_VCS_FILES;
16192 $this->ignore &= ~static::IGNORE_VCS_FILES;
16198 foreach ((array) $pattern as $p) {
16199 self::$vcsPatterns[] = $p;
16201 self::$vcsPatterns = array_unique(self::$vcsPatterns);
16203 public function sort(\Closure $closure)
16205 $this->
sort = $closure;
16210 $this->
sort = Iterator\SortableIterator::SORT_BY_NAME;
16215 $this->
sort = Iterator\SortableIterator::SORT_BY_TYPE;
16220 $this->
sort = Iterator\SortableIterator::SORT_BY_ACCESSED_TIME;
16225 $this->
sort = Iterator\SortableIterator::SORT_BY_CHANGED_TIME;
16230 $this->
sort = Iterator\SortableIterator::SORT_BY_MODIFIED_TIME;
16235 $this->filters[] = $closure;
16240 $this->followLinks =
true;
16245 $this->ignoreUnreadableDirs = (bool) $ignore;
16250 $resolvedDirs = array();
16251 foreach ((array) $dirs as $dir) {
16252 if (is_dir($dir)) {
16253 $resolvedDirs[] = $dir;
16254 } elseif ($glob = glob($dir, GLOB_BRACE | GLOB_ONLYDIR)) {
16255 $resolvedDirs = array_merge($resolvedDirs, $glob);
16257 throw new \InvalidArgumentException(sprintf(
'The "%s" directory does not exist.', $dir));
16260 $this->dirs = array_merge($this->dirs, $resolvedDirs);
16265 if (0 === count($this->dirs) && 0 === count($this->iterators)) {
16266 throw new \LogicException(
'You must call one of in() or append() methods before iterating over a Finder.');
16268 if (1 === count($this->dirs) && 0 === count($this->iterators)) {
16269 return $this->searchInDirectory($this->dirs[0]);
16271 $iterator = new \AppendIterator();
16272 foreach ($this->dirs as $dir) {
16273 $iterator->append($this->searchInDirectory($dir));
16275 foreach ($this->iterators as $it) {
16276 $iterator->append($it);
16282 if ($iterator instanceof \IteratorAggregate) {
16283 $this->iterators[] = $iterator->getIterator();
16284 } elseif ($iterator instanceof \Iterator) {
16285 $this->iterators[] = $iterator;
16286 } elseif ($iterator instanceof \Traversable || is_array($iterator)) {
16287 $it = new \ArrayIterator();
16288 foreach ($iterator as $file) {
16289 $it->append($file instanceof \SplFileInfo ? $file :
new \SplFileInfo($file));
16291 $this->iterators[] = $it;
16293 throw new \InvalidArgumentException(
'Finder::append() method wrong argument type.');
16299 return iterator_count($this->getIterator());
16301 private function sortAdapters()
16303 uasort($this->adapters,
function (array
$a, array
$b) {
16304 if ($a[
'selected'] || $b[
'selected']) {
16305 return $a[
'selected'] ? -1 : 1;
16307 return $a[
'priority'] > $b[
'priority'] ? -1 : 1;
16311 private function searchInDirectory($dir)
16313 if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) {
16314 $this->exclude = array_merge($this->exclude, self::$vcsPatterns);
16316 if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) {
16317 $this->notPaths[] =
'#(^|/)\\..+(/|$)#';
16319 foreach ($this->adapters as $adapter) {
16320 if ($adapter[
'adapter']->isSupported()) {
16322 return $this->buildAdapter($adapter[
'adapter'])->searchInDirectory($dir);
16323 }
catch (ExceptionInterface $e) {
16327 throw new \RuntimeException(
'No supported adapter found.');
16329 private function buildAdapter(AdapterInterface $adapter)
16331 return $adapter->setFollowLinks($this->followLinks)->setDepths($this->depths)->setMode($this->mode)->setExclude($this->exclude)->setNames($this->names)->setNotNames($this->notNames)->setContains($this->
contains)->setNotContains($this->notContains)->setSizes($this->sizes)->setDates($this->dates)->setFilters($this->filters)->setSort($this->
sort)->setPath($this->paths)->setNotPath($this->notPaths)->ignoreUnreadableDirs($this->ignoreUnreadableDirs);
16333 private function resetAdapterSelection()
16335 $this->adapters = array_map(
function (array $properties) {
16336 $properties[
'selected'] =
false;
16337 return $properties;
16338 }, $this->adapters);
16348 use InvalidArgumentException;
16357 const WEDNESDAY = 3;
16358 const THURSDAY = 4;
16360 const SATURDAY = 6;
16361 protected static $days = array(self::SUNDAY =>
'Sunday', self::MONDAY =>
'Monday', self::TUESDAY =>
'Tuesday', self::WEDNESDAY =>
'Wednesday', self::THURSDAY =>
'Thursday', self::FRIDAY =>
'Friday', self::SATURDAY =>
'Saturday');
16362 protected static $relativeKeywords = array(
'this',
'next',
'last',
'tomorrow',
'yesterday',
'+',
'-',
'first',
'last',
'ago');
16363 const YEARS_PER_CENTURY = 100;
16364 const YEARS_PER_DECADE = 10;
16365 const MONTHS_PER_YEAR = 12;
16366 const WEEKS_PER_YEAR = 52;
16367 const DAYS_PER_WEEK = 7;
16368 const HOURS_PER_DAY = 24;
16369 const MINUTES_PER_HOUR = 60;
16370 const SECONDS_PER_MINUTE = 60;
16371 const DEFAULT_TO_STRING_FORMAT =
'Y-m-d H:i:s';
16372 protected static $toStringFormat = self::DEFAULT_TO_STRING_FORMAT;
16377 if ($object === null) {
16378 return new DateTimeZone(date_default_timezone_get());
16380 if ($object instanceof DateTimeZone) {
16383 $tz = @timezone_open((
string) $object);
16384 if ($tz ===
false) {
16385 throw new InvalidArgumentException(
'Unknown or bad timezone (' . $object .
')');
16391 if (static::hasTestNow() && (
empty($time) || $time ===
'now' || static::hasRelativeKeywords($time))) {
16392 $testInstance = clone static::getTestNow();
16393 if (static::hasRelativeKeywords($time)) {
16394 $testInstance->modify($time);
16396 if ($tz !== NULL && $tz != static::getTestNow()->tz) {
16397 $testInstance->setTimezone($tz);
16399 $tz = $testInstance->tz;
16401 $time = $testInstance->toDateTimeString();
16403 parent::__construct($time, static::safeCreateDateTimeZone($tz));
16407 return new static($dt->format(
'Y-m-d H:i:s.u'), $dt->getTimeZone());
16409 public static function parse($time = null, $tz = null)
16411 return new static($time, $tz);
16413 public static function now($tz = null)
16415 return new static(null, $tz);
16423 return static::today($tz)->addDay();
16427 return static::today($tz)->subDay();
16431 return static::createFromTimestamp(PHP_INT_MAX);
16435 return static::createFromTimestamp(~PHP_INT_MAX);
16437 public static function create($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null)
16439 $year = $year === null ? date(
'Y') : $year;
16440 $month = $month === null ? date(
'n') : $month;
16441 $day = $day === null ? date(
'j') : $day;
16442 if ($hour === null) {
16444 $minute = $minute === null ? date(
'i') : $minute;
16445 $second = $second === null ? date(
's') : $second;
16447 $minute = $minute === null ? 0 : $minute;
16448 $second = $second === null ? 0 : $second;
16450 return static::createFromFormat(
'Y-n-j G:i:s', sprintf(
'%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $tz);
16452 public static function createFromDate($year = null, $month = null, $day = null, $tz = null)
16454 return static::create($year, $month, $day, null, null, null, $tz);
16456 public static function createFromTime($hour = null, $minute = null, $second = null, $tz = null)
16458 return static::create(null, null, null, $hour, $minute, $second, $tz);
16462 if ($tz !== null) {
16463 $dt = parent::createFromFormat($format, $time, static::safeCreateDateTimeZone($tz));
16465 $dt = parent::createFromFormat($format, $time);
16467 if ($dt instanceof DateTime) {
16468 return static::instance($dt);
16470 $errors = static::getLastErrors();
16471 throw new InvalidArgumentException(implode(PHP_EOL, $errors[
'errors']));
16475 return static::now($tz)->setTimestamp($timestamp);
16479 return new static(
'@' . $timestamp);
16483 return static::instance($this);
16488 case array_key_exists($name, $formats = array(
'year' =>
'Y',
'yearIso' =>
'o',
'month' =>
'n',
'day' =>
'j',
'hour' =>
'G',
'minute' =>
'i',
'second' =>
's',
'micro' =>
'u',
'dayOfWeek' =>
'w',
'dayOfYear' =>
'z',
'weekOfYear' =>
'W',
'daysInMonth' =>
't',
'timestamp' =>
'U')):
16489 return (
int) $this->
format($formats[$name]);
16490 case $name ===
'weekOfMonth':
16491 return (
int) ceil($this->
day / static::DAYS_PER_WEEK);
16492 case $name ===
'age':
16493 return (
int) $this->diffInYears();
16494 case $name ===
'quarter':
16495 return (
int) ceil($this->
month / 3);
16496 case $name ===
'offset':
16497 return $this->getOffset();
16498 case $name ===
'offsetHours':
16499 return $this->getOffset() / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR;
16500 case $name ===
'dst':
16501 return $this->
format(
'I') ==
'1';
16502 case $name ===
'local':
16503 return $this->offset == $this->copy()->setTimezone(date_default_timezone_get())->offset;
16504 case $name ===
'utc':
16505 return $this->offset == 0;
16506 case $name ===
'timezone' || $name ===
'tz':
16507 return $this->getTimezone();
16508 case $name ===
'timezoneName' || $name ===
'tzName':
16509 return $this->getTimezone()->getName();
16511 throw new InvalidArgumentException(sprintf(
'Unknown getter \'%s\'', $name));
16517 $this->__get($name);
16518 }
catch (InvalidArgumentException $e) {
16527 $this->setDate($value, $this->
month, $this->
day);
16530 $this->setDate($this->
year, $value, $this->
day);
16533 $this->setDate($this->
year, $this->
month, $value);
16539 $this->setTime($this->
hour, $value, $this->
second);
16542 $this->setTime($this->
hour, $this->
minute, $value);
16545 parent::setTimestamp($value);
16549 $this->setTimezone($value);
16552 throw new InvalidArgumentException(sprintf(
'Unknown setter \'%s\'', $name));
16557 $this->
year = $value;
16562 $this->
month = $value;
16567 $this->
day = $value;
16572 $this->
hour = $value;
16585 public function setDateTime($year, $month, $day, $hour, $minute, $second = 0)
16587 return $this->setDate($year, $month, $day)->setTime($hour, $minute, $second);
16591 $this->timestamp = $value;
16596 return $this->setTimezone($value);
16600 return $this->setTimezone($value);
16604 parent::setTimezone(static::safeCreateDateTimeZone($value));
16609 static::$testNow = $testNow;
16613 return static::$testNow;
16617 return static::getTestNow() !== null;
16621 if (preg_match(
'/[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}/', $time) !== 1) {
16622 foreach (static::$relativeKeywords as $keyword) {
16623 if (stripos($time, $keyword) !==
false) {
16632 if (static::$translator == null) {
16634 static::$translator->addLoader(
'array',
new ArrayLoader());
16635 static::setLocale(
'en');
16637 return static::$translator;
16641 return static::translator();
16645 static::$translator = $translator;
16649 return static::translator()->getLocale();
16653 static::translator()->setLocale($locale);
16654 static::translator()->addResource(
'array', require
'/Users/ket/Desktop/VirtualScada/virtualscada_laravel/vendor/nesbot/carbon/src/Carbon' .
'/Lang/' . $locale .
'.php', $locale);
16658 if (strtoupper(substr(PHP_OS, 0, 3)) ==
'WIN') {
16659 $format = preg_replace(
'#(?<!%)((?:%%)*)%e#',
'\\1%#d', $format);
16661 return strftime($format, strtotime($this));
16665 static::setToStringFormat(static::DEFAULT_TO_STRING_FORMAT);
16669 static::$toStringFormat = $format;
16673 return $this->
format(static::$toStringFormat);
16677 return $this->
format(
'Y-m-d');
16681 return $this->
format(
'M j, Y');
16685 return $this->
format(
'H:i:s');
16689 return $this->
format(
'Y-m-d H:i:s');
16693 return $this->
format(
'D, M j, Y g:i A');
16697 return $this->
format(static::ATOM);
16701 return $this->
format(static::COOKIE);
16705 return $this->
format(static::ISO8601);
16709 return $this->
format(static::RFC822);
16713 return $this->
format(static::RFC850);
16717 return $this->
format(static::RFC1036);
16721 return $this->
format(static::RFC1123);
16725 return $this->
format(static::RFC2822);
16729 return $this->
format(static::RFC3339);
16733 return $this->
format(static::RSS);
16737 return $this->
format(static::W3C);
16741 return $this == $dt;
16745 return !$this->eq($dt);
16749 return $this > $dt;
16753 return $this >= $dt;
16757 return $this < $dt;
16761 return $this <= $dt;
16765 if ($dt1->
gt($dt2)) {
16771 return $this->gte($dt1) && $this->lte($dt2);
16773 return $this->gt($dt1) && $this->lt($dt2);
16778 $dt = $dt === null ?
static::now($this->tz) : $dt;
16779 return $this->lt($dt) ? $this : $dt;
16783 $dt = $dt === null ?
static::now($this->tz) : $dt;
16784 return $this->gt($dt) ? $this : $dt;
16788 return $this->dayOfWeek != static::SUNDAY && $this->dayOfWeek != static::SATURDAY;
16792 return !$this->isWeekDay();
16796 return $this->toDateString() === static::yesterday($this->tz)->toDateString();
16800 return $this->toDateString() ===
static::now($this->tz)->toDateString();
16804 return $this->toDateString() === static::tomorrow($this->tz)->toDateString();
16816 return $this->
format(
'L') ==
'1';
16824 return $this->modify((
int) $value .
' year');
16828 return $this->addYears($value);
16832 return $this->subYears($value);
16836 return $this->addYears(-1 * $value);
16840 return $this->modify((
int) $value .
' month');
16844 return $this->addMonths($value);
16848 return $this->subMonths($value);
16852 return $this->addMonths(-1 * $value);
16856 $date = $this->copy()->addMonths($value);
16857 if ($date->day != $this->day) {
16858 $date->day(1)->subMonth()->day($date->daysInMonth);
16864 return $this->addMonthsNoOverflow($value);
16868 return $this->subMonthsNoOverflow($value);
16872 return $this->addMonthsNoOverflow(-1 * $value);
16876 return $this->modify((
int) $value .
' day');
16880 return $this->addDays($value);
16884 return $this->subDays($value);
16888 return $this->addDays(-1 * $value);
16892 return $this->modify((
int) $value .
' weekday');
16896 return $this->addWeekdays($value);
16900 return $this->subWeekdays($value);
16904 return $this->addWeekdays(-1 * $value);
16908 return $this->modify((
int) $value .
' week');
16912 return $this->addWeeks($value);
16916 return $this->subWeeks($value);
16920 return $this->addWeeks(-1 * $value);
16924 return $this->modify((
int) $value .
' hour');
16928 return $this->addHours($value);
16932 return $this->subHours($value);
16936 return $this->addHours(-1 * $value);
16940 return $this->modify((
int) $value .
' minute');
16944 return $this->addMinutes($value);
16948 return $this->subMinutes($value);
16952 return $this->addMinutes(-1 * $value);
16956 return $this->modify((
int) $value .
' second');
16960 return $this->addSeconds($value);
16964 return $this->subSeconds($value);
16968 return $this->addSeconds(-1 * $value);
16972 $dt = $dt === null ?
static::now($this->tz) : $dt;
16973 return (
int) $this->diff($dt, $abs)->format(
'%r%y');
16977 $dt = $dt === null ?
static::now($this->tz) : $dt;
16978 return $this->diffInYears($dt, $abs) * static::MONTHS_PER_YEAR + (int) $this->diff($dt, $abs)->format(
'%r%m');
16982 return (
int) ($this->diffInDays($dt, $abs) / static::DAYS_PER_WEEK);
16986 $dt = $dt === null ?
static::now($this->tz) : $dt;
16987 return (
int) $this->diff($dt, $abs)->format(
'%r%a');
17000 $end = $dt === null ?
static::now($this->tz) : $dt;
17007 $period =
new DatePeriod(
$start, $ci, $end);
17008 $vals = array_filter(iterator_to_array($period),
function (DateTime $date) use($callback) {
17009 return call_user_func($callback, Carbon::instance($date));
17011 $diff = count($vals);
17012 return $inverse && !$abs ? -$diff :
$diff;
17016 return $this->diffInDaysFiltered(
function (
Carbon $date) {
17022 return $this->diffInDaysFiltered(
function (
Carbon $date) {
17028 return (
int) ($this->diffInSeconds($dt, $abs) / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR);
17032 return (
int) ($this->diffInSeconds($dt, $abs) / static::SECONDS_PER_MINUTE);
17036 $dt = $dt === null ?
static::now($this->tz) : $dt;
17037 $value = $dt->getTimestamp() - $this->getTimestamp();
17038 return $abs ? abs($value) : $value;
17042 return $this->diffInSeconds($this->copy()->startOfDay());
17046 return $this->diffInSeconds($this->copy()->endOfDay());
17050 $isNow = $other === null;
17054 $diffInterval = $this->diff($other);
17056 case $diffInterval->y > 0:
17058 $count = $diffInterval->y;
17060 case $diffInterval->m > 0:
17062 $count = $diffInterval->m;
17064 case $diffInterval->d > 0:
17066 $count = $diffInterval->d;
17067 if (
$count >= self::DAYS_PER_WEEK) {
17072 case $diffInterval->h > 0:
17074 $count = $diffInterval->h;
17076 case $diffInterval->i > 0:
17078 $count = $diffInterval->i;
17081 $count = $diffInterval->s;
17088 $time = static::translator()->transChoice($unit,
$count, array(
':count' =>
$count));
17092 $isFuture = $diffInterval->invert === 1;
17093 $transId = $isNow ? $isFuture ?
'from_now' :
'ago' : ($isFuture ?
'after' :
'before');
17094 $tryKeyExists = $unit .
'_' . $transId;
17095 if ($tryKeyExists !== static::translator()->transChoice($tryKeyExists,
$count)) {
17096 $time = static::translator()->transChoice($tryKeyExists,
$count, array(
':count' =>
$count));
17098 return static::translator()->trans($transId, array(
':time' => $time));
17102 return $this->
hour(0)->minute(0)->second(0);
17106 return $this->
hour(23)->minute(59)->second(59);
17110 return $this->startOfDay()->day(1);
17114 return $this->
day($this->daysInMonth)->endOfDay();
17118 return $this->
month(1)->startOfMonth();
17122 return $this->
month(static::MONTHS_PER_YEAR)->endOfMonth();
17126 return $this->startOfYear()->year($this->
year - $this->
year % static::YEARS_PER_DECADE);
17130 return $this->endOfYear()->year($this->
year - $this->
year % static::YEARS_PER_DECADE + static::YEARS_PER_DECADE - 1);
17134 return $this->startOfYear()->year($this->
year - $this->
year % static::YEARS_PER_CENTURY);
17138 return $this->endOfYear()->year($this->
year - $this->
year % static::YEARS_PER_CENTURY + static::YEARS_PER_CENTURY - 1);
17142 if ($this->dayOfWeek != static::MONDAY) {
17143 $this->previous(static::MONDAY);
17145 return $this->startOfDay();
17149 if ($this->dayOfWeek != static::SUNDAY) {
17150 $this->next(static::SUNDAY);
17152 return $this->endOfDay();
17154 public function next($dayOfWeek = null)
17156 if ($dayOfWeek === null) {
17157 $dayOfWeek = $this->dayOfWeek;
17159 return $this->startOfDay()->modify(
'next ' . static::$days[$dayOfWeek]);
17163 if ($dayOfWeek === null) {
17164 $dayOfWeek = $this->dayOfWeek;
17166 return $this->startOfDay()->modify(
'last ' . static::$days[$dayOfWeek]);
17170 $this->startOfDay();
17171 if ($dayOfWeek === null) {
17172 return $this->
day(1);
17174 return $this->modify(
'first ' . static::$days[$dayOfWeek] .
' of ' . $this->
format(
'F') .
' ' . $this->
year);
17178 $this->startOfDay();
17179 if ($dayOfWeek === null) {
17180 return $this->
day($this->daysInMonth);
17182 return $this->modify(
'last ' . static::$days[$dayOfWeek] .
' of ' . $this->
format(
'F') .
' ' . $this->
year);
17186 $dt = $this->copy()->firstOfMonth();
17187 $check = $dt->format(
'Y-m');
17188 $dt->modify(
'+' . $nth .
' ' . static::$days[$dayOfWeek]);
17189 return $dt->format(
'Y-m') === $check ? $this->modify($dt) :
false;
17193 return $this->
day(1)->month($this->quarter * 3 - 2)->firstOfMonth($dayOfWeek);
17197 return $this->
day(1)->month($this->quarter * 3)->lastOfMonth($dayOfWeek);
17201 $dt = $this->copy()->day(1)->month($this->quarter * 3);
17202 $last_month = $dt->month;
17204 $dt->firstOfQuarter()->modify(
'+' . $nth .
' ' . static::$days[$dayOfWeek]);
17205 return $last_month < $dt->month || $year !== $dt->year ?
false : $this->modify($dt);
17209 return $this->
month(1)->firstOfMonth($dayOfWeek);
17213 return $this->
month(static::MONTHS_PER_YEAR)->lastOfMonth($dayOfWeek);
17217 $dt = $this->copy()->firstOfYear()->modify(
'+' . $nth .
' ' . static::$days[$dayOfWeek]);
17218 return $this->
year == $dt->year ? $this->modify($dt) :
false;
17222 $dt = $dt === null ?
static::now($this->tz) : $dt;
17223 return $this->addSeconds((
int) ($this->diffInSeconds($dt,
false) / 2));
17227 return $this->
format(
'md') === $dt->format(
'md');
17233 class AppServiceProvider
extends ServiceProvider
17238 public function register()
17240 $this->app->bind(
'Illuminate\\Contracts\\Auth\\Registrar',
'App\\Services\\Registrar');
17247 class BusServiceProvider
extends ServiceProvider
17251 $dispatcher->
mapUsing(
function ($command) {
17252 return Dispatcher::simpleMapping($command,
'App\\Commands',
'App\\Handlers\\Commands');
17255 public function register()
17262 class ConfigServiceProvider
extends ServiceProvider
17264 public function register()
17273 class EventServiceProvider
extends ServiceProvider
17275 protected $listen = array(
'event.name' => array(
'EventListener'));
17276 public function boot(DispatcherContract $events)
17278 parent::boot($events);
17285 class RouteServiceProvider
extends ServiceProvider
17287 protected $namespace =
'App\\Http\\Controllers';
17290 parent::boot($router);
17294 $router->
group(array(
'namespace' => $this->
namespace),
function ($router) {
17295 require app_path(
'Http/routes.php');
input($key, $default=null)
static except($array, $keys)
duplicate(array $query=null, array $request=null, array $attributes=null, array $cookies=null, array $files=null, array $server=null)
compileEndunless($expression)
afterBootstrapping($bootstrapper, Closure $callback)
static hydrateRaw($query, $bindings=array(), $connection=null)
static getTrustedHeaderName($key)
hasMany($related, $foreignKey=null, $localKey=null)
boot(Dispatcher $dispatcher)
static getFacadeAccessor()
notice($message, array $context=array())
isDirty($attributes=null)
splice($offset, $length=0, $replacement=array())
replace(array $attributes)
convertToControllerAction($action)
filter(callable $callback)
dispatchNow($command, Closure $afterResolving=null)
static __callStatic($method, $parameters)
diffInDays(Carbon $dt=null, $abs=true)
replaceRoutableParameters($parameters=array())
missingMethod($parameters=array())
static setRouter(Router $router)
singleton($abstract, $concrete=null)
static firstOrCreate(array $attributes)
setDispatcher(Dispatcher $events)
static getFacadeAccessor()
removeObservableEvents($observables)
bootstrap(Application $app)
header($key=null, $default=null)
static saved($callback, $priority=0)
transform(callable $callback)
sortByDesc($callback, $options=SORT_REGULAR)
addFallthroughRoute($controller, $uri)
static create($content= '', $status=200, $headers=array())
handlerShouldBeQueued($class)
dispatch($command, Closure $afterResolving=null)
subMonthsNoOverflow($value)
callQueueMethodOnHandler($class, $method, $arguments)
__construct(ViewFactory $view)
setCookieJar(CookieJar $cookie)
bind($abstract, $concrete=null, $shared=false)
beforeFilter($filter, array $options=array())
filterFailsMethod($filter, $request, $method)
handle(SymfonyRequest $request, $type=self::MASTER_REQUEST, $catch=true)
callWithinStack($instance, $route, $request, $method)
getAttributeFromArray($key)
__construct(Container $container)
retrieveByCredentials(array $credentials)
static setFacadeApplication($app)
static setLocale($locale)
compileExtensions($value)
startSession(Request $request)
callClass($target, array $parameters=array(), $defaultMethod=null)
make($abstract, $parameters=array())
__construct($file, $relativePath, $relativePathname)
renderException($request, Exception $e)
subMonthNoOverflow($value=1)
addObservableEvents($observables)
getOriginal($key=null, $default=null)
first($key=null, $format=null)
shouldRecompile($manifest, $providers)
registerValidationFactory()
morphedByMany($related, $name, $table=null, $foreignKey=null, $otherKey=null)
forceFill(array $attributes)
emerg($message, array $context=array())
diffForHumans(Carbon $other=null, $absolute=false)
static onWriteConnection()
isInstanceFilter($filter)
contains($key, $value=null)
findInPaths($name, $paths)
fireAppCallbacks(array $callbacks)
static clearResolvedInstance($name)
isDeferredService($service)
prependMiddleware($middleware)
replace(array $parameters=array())
static explodeArrayFilters(array $filters)
setPdoForType(Connection $connection, $type=null)
syncOriginalAttribute($attribute)
check(array $routes, $request, $includingMethod=true)
crit($message, array $context=array())
warning($message, array $context=array())
marshal($command, ArrayAccess $source, array $extras=array())
static load($path, $file= '.env')
setSession(SessionInterface $session)
useFiles($path, $level= 'debug')
mergeConfigFrom($path, $key)
static set(&$array, $key, $value)
extractAlias(array $definition)
rebinding($abstract, Closure $callback)
getReadWriteConfig(array $config, $type)
createResponse($exception)
originalIsNumericallyEquivalent($key)
updateRememberToken(UserContract $user, $token)
morphMany($related, $name, $type=null, $id=null, $localKey=null)
static formatGroupPrefix($new, $old)
if(0!==$parseFail) if(0!==$ppFail) $count
parseConfig(array $config, $name)
static createFromFormat($format, $time, $tz=null)
get($key, $default=null, $deep=false)
__construct(array $parameters=array())
buildFindCommand(Command $command, $dir)
dispatchFrom($command, ArrayAccess $source, array $extras=array())
query($key=null, $default=null)
setExpires(\DateTime $date=null)
setRequirement($key, $regex)
static getInstance(array $aliases=array())
handle($request, Closure $next)
compileForelse($expression)
deleteDirectory($directory, $preserve=false)
createClassBinding($binding)
once(array $credentials=array())
handle($request, Closure $next)
static getTrustedProxies()
registerBladeEngine($resolver)
yieldContent($section, $default= '')
static on($connection=null)
compileInclude($expression)
registerConfiguredProviders()
firstOfQuarter($dayOfWeek=null)
addDependencyForCallParameter(ReflectionParameter $parameter, array &$parameters, &$dependencies)
static getMockableClass()
buildFormatSorting(Command $command, $sort)
addExtension($extension, $engine, $resolver=null)
setRawTags($openTag, $closeTag)
screamAt($levels, $replace=false)
setLoggers(array $loggers)
handleViewException($e, $obLevel)
removeFilter($removing, $current)
commandShouldBeQueued($command)
updateGroupStack(array $attributes)
__construct(array $query=array(), array $request=array(), array $attributes=array(), array $cookies=array(), array $files=array(), array $server=array(), $content=null)
__construct($name, array $handlers=array(), array $processors=array())
write($level, $message, array $context=array())
getRouteRoot($route, $domain)
compileSection($expression)
onceBasic($field= 'email')
diffInYears(Carbon $dt=null, $abs=true)
gatherRouteMiddlewares(Route $route)
__construct($time=null, $tz=null)
registerCoreContainerAliases()
resource($name, $controller, array $options=array())
handleViewException($e, $obLevel)
compileExtends($expression)
registerClosureFilter(Closure $filter)
alert($message, array $context=array())
decrypt(Request $request)
diffInWeekdays(Carbon $dt=null, $abs=true)
static is($pattern, $value)
static createFromTime($hour=null, $minute=null, $second=null, $tz=null)
where($column, $operator=null, $value=null, $boolean= 'and')
where($name, $expression=null)
addInfo($message, array $context=array())
decrement($column, $amount=1)
when($pattern, $name, $methods=null)
vendorIsWritableForOptimizations()
resolving($abstract, Closure $callback=null)
registerDeferredProvider($provider, $service=null)
log($level, $message, array $context=array())
setNotNames(array $notNames)
boot(DispatcherContract $events)
make($value, array $options=array())
getSession(Request $request)
registerInspected($route, $controller, $method, &$names)
setVary($headers, $replace=true)
setKeysForSaveQuery(Builder $query)
matches(Request $request, $includingMethod=true)
static safeCreateDateTimeZone($object)
setRoutes(RouteCollection $routes)
createRememberTokenIfDoesntExist(UserContract $user)
bindIf($abstract, $concrete=null, $shared=false)
decryptArray(array $cookie)
setFollowLinks($followLinks)
getMappingSegment($className, $segment)
addWhereClausesToRoute($route)
handle($level, $message, $file= 'unknown', $line=0, $context=array())
callRouteBefore($route, $request)
matches(Route $route, Request $request)
duplicate(Cookie $c, $value)
static setLogger(LoggerInterface $logger, $channel= 'deprecation')
log($level, $message, array $context=array())
static getFacadeApplication()
useSyslog($name= 'laravel', $level= 'debug')
getDependencies($parameters, array $primitives=array())
handleError($type, $message, $file, $line, array $context)
instance($abstract, $instance)
registerConfiguredProviders()
copyDirectory($directory, $destination, $options=null)
static forget(&$array, $keys)
instance($abstract, $instance)
static findOrNew($id, $columns=array('*'))
parseConnectionName($name)
getAlpha($key, $default= '', $deep=false)
addAdapter(AdapterInterface $adapter, $priority=0)
Bo ya ya ya ya ya ya ya ya ya ya ya ya filter
terminating(Closure $callback)
bootstrap(Application $app)
addClassEvent($view, $class, $prefix, $priority=null)
afterResolvingCallback(Closure $callback)
beforeBootstrapping($bootstrapper, Closure $callback)
static unsetEventDispatcher()
makeController($controller)
configHitsLottery(array $config)
cleanFilterParameters(array $parameters)
__construct($path, $flags, $ignoreUnreadableDirs=false)
diffInWeeks(Carbon $dt=null, $abs=true)
castAttribute($key, $value)
handle($request, Closure $next)
__construct(MonologLogger $monolog, Dispatcher $dispatcher=null)
static instance(DateTime $dt)
detect(Closure $callback, $consoleArgs=null)
setContains(array $contains)
error($message, array $context=array())
middleware($name, $class)
removeGlobalScopes($builder)
asset($path, $secure=null)
setFilenameFormat($filenameFormat, $dateFormat)
__call($method, $parameters)
__call($method, $parameters)
setFileLinkFormat($format)
add(array $parameters=array())
setEscapedContentTags($openTag, $closeTag)
__construct($pattern, $options= '', $delimiter=null)
static first($array, callable $callback, $default=null)
addCritical($message, array $context=array())
lastOfQuarter($dayOfWeek=null)
__construct(SessionManager $manager)
static setToStringFormat($format)
addRequirements(array $requirements)
filterApplies($filter, $request, $method)
static unguarded(callable $callback)
methodExcludedByOptions($method, array $options)
static saving($callback, $priority=0)
make($abstract, $parameters=array())
setRawAttributes(array $attributes, $sync=false)
__construct(array $parameters=array())
reportException(Exception $e)
parameter($name, $default=null)
static dot($array, $prepend= '')
nest($key, $view, array $data=array())
old($key=null, $default=null)
getParameter($name, $default=null)
getRoutable($controller, $prefix)
static getLevelName($level)
getClosure($abstract, $concrete)
isBuildable($concrete, $abstract)
fireResolvingCallbacks($abstract, $object)
secure($path, $parameters=array())
push($event, $payload=array())
setUserResolver(Closure $callback)
postRegister(Request $request)
morphOne($related, $name, $type=null, $id=null, $localKey=null)
keyParametersByArgument(array $dependencies, array $parameters)
hasOne($related, $foreignKey=null, $localKey=null)
static hydrate(array $items, $connection=null)
extend($abstract, Closure $closure)
call($instance, $route, $method)
info($message, array $context=array())
registerNativeFilesystem()
paddingIsValid($pad, $value)
setStartJoker($startJoker)
addVisible($attributes=null)
formatParameters($parameters)
setRelations(array $relations)
addDebug($message, array $context=array())
createOpenMatcher($function)
static initializeFormats()
seed($class= 'DatabaseSeeder')
whereArray(array $wheres)
createConnector(array $config)
compileEndif($expression)
postEmail(Request $request)
compileStatements($value)
performBinding($key, $value, $route)
setFinder(ViewFinderInterface $finder)
static startsWith($haystack, $needles)
isHandling(array $record)
retrieveByToken($identifier, $token)
addNamespace($namespace, $hints)
compileWhile($expression)
addCookieToResponse(Response $response, SessionInterface $session)
makeDirectory($path, $mode=493, $recursive=false, $force=false)
Bo Bo Bo Bo Bo Bo Bo Bo Bo keys
getConfigurationFiles(Application $app)
needsRehash($hashedValue, array $options=array())
increment($column, $amount=1)
getEnvironmentArgument(array $args)
__construct(ApplicationContract $app, Filesystem $files, $manifestPath)
setFormat($format, $mimeTypes)
setRequestOnHandler(Request $request)
__construct($seedFile=null, LoggerInterface $logger=null)
createReadWriteConnection(array $config)
retrieveById($identifier)
registerValidationResolverHook()
cleanDirectory($directory)
static updating($callback, $priority=0)
inject($section, $content)
finishSave(array $options)
__construct(ContainerContract $container=null)
prependNamespace($namespace, $hints)
static find($id, $columns=array('*'))
matchToKeys(array $matches)
make($abstract, $parameters=array())
static limit($value, $limit=100, $end= '...')
queueRecallerCookie(UserContract $user)
convertFileInformation($file)
resolveProviderClass($provider)
getRootUrl($scheme, $root=null)
addContextualBinding($concrete, $abstract, $implementation)
fillable(array $fillable)
static add($array, $key, $value)
createConnection($driver, PDO $connection, $database, $prefix= '', array $config=array())
compileYield($expression)
ensureIEOverSSLCompatibility(Request $request)
extractOptionalParameters()
fresh(array $with=array())
Bo ya ya ya ya ya ya ya ya ya ya ya ya ya ya ya ya call
insertAndSetId(Builder $query, $attributes)
callCustomCreator($driver)
resolving($abstract, Closure $callback=null)
createPlainMatcher($function)
runCallable(Request $request)
static getFacadeAccessor()
Bo Bo Bo Bo Bo Bo Bo Bo Bo Bo Bo Bo merge
static clearResolvedInstances()
static closeOutputBuffers($targetLevel, $flush)
ignoreDotFiles($ignoreDotFiles)
forgetBeforeFilter($filter)
registerBaseServiceProviders()
slice($offset, $length=null, $preserveKeys=false)
getPreviousUrlFromSession()
build($concrete, $parameters=array())
__construct(Filesystem $files, $cachePath)
replaceNamedParameters($path, &$parameters)
__call($method, $parameters)
findPatternFilters($request)
getCallReflector($callback)
getBoolean($key, $default=false, $deep=false)
static words($value, $words=100, $end= '...')
setExclude(array $exclude)
cookie($key=null, $default=null)
createCacheHandler($driver)
static cacheMutatedAttributes($class)
static tomorrow($tz=null)
createRoute($methods, $uri, $action)
static yesterday($tz=null)
match($methods, $uri, $action)
useDailyFiles($path, $days=0, $level= 'debug')
registerLoadEvents($provider, array $events)
__construct(Container $container)
inflectSegment($command, $segment)
route($name, $parameters=array(), $absolute=true)
pushMiddleware($middleware)
static getGlobalScope($scope)
fireAttemptEvent(array $credentials, $remember, $login)
setDeferredServices(array $services)
parseFilter($filter, array $options)
setRequest(Request $request)
removeFromOldFlashData(array $keys)
static deleted($callback, $priority=0)
loadDeferredProvider($service)
jl Io Io rc rc rc seconds rc minute
mcryptDecrypt($value, $iv)
fillableFromArray(array $attributes)
if(!file_exists($kmyacc)) $options
static deleting($callback, $priority=0)
afterResolving($abstract, Closure $callback=null)
setEtag($etag=null, $weak=false)
handleError($level, $message, $file= '', $line=0, $context=array())
setRequest(Request $request)
diffInHours(Carbon $dt=null, $abs=true)
getHandlerMethod($command)
getInitialSlice(Closure $destination)
static handleFatalError(array $error=null)
__construct(Encrypter $encrypter)
getUserByRecaller($recaller)
shared($key, $default=null)
isRoutable(ReflectionMethod $method)
encrypt(Response $response)
filterSupportsMethod($filter, $method)
ignoreUnreadableDirs($ignore=true)
evaluatePath($__path, $__data)
middleware($middleware, array $options=array())
Bo Bo behavior Bo touches
static pathsToPublish($provider=null, $group=null)
__construct(\Iterator $iterator, array $directories)
mutateAttribute($key, $value)
__construct(array $attributes=array())
model($key, $class, Closure $callback=null)
incrementOrDecrementAttributeValue($column, $amount, $method)
compileUnless($expression)
setLastModified(\DateTime $date=null)
extend(callable $compiler)
extend($name, callable $resolver)
resources(array $resources)
static explodeFilters($filters)
json($key=null, $default=null)
static endsWith($haystack, $needles)
segment($index, $default=null)
static pluck($array, $value, $key=null)
controller($uri, $controller, $names=array())
getRelationshipFromMethod($method)
between(Carbon $dt1, Carbon $dt2, $equal=true)
fatalExceptionFromError(array $error, $traceOffset=null)
isNotModified(Request $request)
update(array $attributes=array())
offsetSet($offset, $value)
missingLeadingSlash($abstract)
addOptions(array $options)
put($path, $contents, $lock=false)
initialize(array $query=array(), array $request=array(), array $attributes=array(), array $cookies=array(), array $files=array(), array $server=array(), $content=null)
fireModelEvent($event, $halt=true)
error($message, array $context=array())
createCacheBased($driver)
__construct(RouteCollection $routes, Request $request)
morphTo($name=null, $type=null, $id=null)
createClassListener($listener)
setRelation($relation, $value)
addRecord($level, $message, array $context=array())
throwAt($levels, $replace=false)
filterFailsOn($filter, $request, $method)
static equals($knownString, $userInput)
nthOfQuarter($nth, $dayOfWeek)
replicate(array $except=null)
markAsRegistered($provider)
buildClassEventCallback($class, $prefix)
getMorphs($name, $type, $id)
runRouteWithinStack(Route $route, Request $request)
__construct(CookieJar $cookies)
static mergeGroup($new, $old)
bindHostParameters(Request $request, $parameters)
static setTrustedHosts(array $hostPatterns)
bootstrap(Application $app)
terminate($request, $response)
getStringParameters(array $parameters)
loadEnvironmentFrom($file)
getPreferredLanguage(array $locales=null)
static createFromTimestamp($timestamp, $tz=null)
static registerModelEvent($event, $callback, $priority=0)
flushSectionsIfDoneRendering()
bindShared($abstract, Closure $closure)
fireLoginEvent($user, $remember=false)
static firstOrNew(array $attributes)
runController(Request $request)
attempt(array $credentials=array(), $remember=false, $login=true)
save(array $options=array())
static contains($haystack, $needles)
invalidate($lifetime=null)
compileEndsection($expression)
static resolveFacadeInstance($name)
resolveNonClass(ReflectionParameter $parameter)
compileEscapedEchos($value)
prepareForSerialization()
refreshRememberToken(UserContract $user)
getPathAndDomain($path, $domain)
newEloquentBuilder($query)
validateCredentials(UserContract $user, array $credentials)
chunk($size, $preserveKeys=false)
diffInHoursFiltered(Closure $callback, Carbon $dt=null, $abs=true)
pull($key, $default=null)
firstOfYear($dayOfWeek=null)
static getConnectionResolver()
diffInMinutes(Carbon $dt=null, $abs=true)
scopeAt($levels, $replace=false)
compileElseif($expression)
static createFromBase($request)
buildContentFiltering(Command $command, array $contains, $not=false)
static setEventDispatcher(Dispatcher $dispatcher)
fireLogEvent($level, $message, array $context=array())
compileEndpush($expression)
group(array $attributes, Closure $callback)
__construct(Factory $factory, EngineInterface $engine, $view, $path, $data=array())
compileEndforeach($expression)
static setConnectionResolver(Resolver $resolver)
Date now(Date.now=function(){return+new Date})
getArrayableItems($items)
getMethodData(ReflectionMethod $method, $prefix)
static createFromBase(SymfonyRequest $request)
handle($request, Closure $next)
getRouteForMethods($request, array $methods)
getRequestFormat($default= 'html')
static creating($callback, $priority=0)
addViewEvent($view, $callback, $prefix= 'composing: ', $priority=null)
__construct(Container $container, Closure $queueResolver=null)
newQueryWithoutScope($scope)
static fetch($array, $key)
compileManifest($providers)
static getHttpMethodParameterOverride()
call($callback, array $parameters=array(), $defaultMethod=null)
compileRegularEchos($value)
compileEndwhile($expression)
firstOfMonth($dayOfWeek=null)
mergeGroupAttributesIntoRoute($route)
getAlnum($key, $default= '', $deep=false)
__construct($filename, $maxFiles=0, $level=Logger::DEBUG, $bubble=true, $filePermission=null, $useLocking=false)
initialize(array &$attributes)
collectGarbage(SessionInterface $session)
setNotContains(array $notContains)
static finish($value, $cap)
afterResolving($abstract, Closure $callback=null)
static createFromGlobals()
handleException(\Exception $exception, array $error=null)
static setTranslator(TranslatorInterface $translator)
buildFormatSorting(Command $command, $sort)
static snake($value, $delimiter= '_')
login(UserContract $user, $remember=false)
static compile(Route $route)
getOldInput($key=null, $default=null)
resolveSubscriber($subscriber)
debug($message, array $context=array())
getWriteConfig(array $config)
setFilters(array $filters)
warn($message, array $context=array())
addCookieToResponse($request, $response)
setDateTime($year, $month, $day, $hour, $minute, $second=0)
addGlobalFilter($filter, $callback)
__construct($stream, $level=Logger::DEBUG, $bubble=true, $filePermission=null, $useLocking=false)
getParameterValueForCommand($command, ArrayAccess $source, ReflectionParameter $parameter, array $extras=array())
bindIf($abstract, $concrete=null, $shared=false)
static setTrustedProxies(array $proxies)
setSessionResolver(callable $sessionResolver)
createProvider($provider)
getArrayableItems(array $values)
fireCallbackArray($object, array $callbacks)
forever($name, $value, $path=null, $domain=null, $secure=false, $httpOnly=true)
static simpleMapping($command, $commandNamespace, $handlerNamespace)
callAction($method, $parameters)
__call($method, $parameters)
afterLoadingEnvironment(Closure $callback)
debug($message, array $context=array())
storeCurrentUrl(Request $request, $session)
__construct($storageKey= '_sf2_attributes')
setDefaultPathAndDomain($path, $domain)
marshalFromArray($command, array $array)
emergency($message, array $context=array())
before($instance, $route, $request, $method)
reduce(callable $callback, $initial=null)
getDigits($key, $default= '', $deep=false)
createClassCallable($listener, $container)
writeLog($level, $message, $context)
addToActionList($action, $route)
critical($message, array $context=array())
setOptions(array $options)
Bo ya ya ya ya ya ya ya ya ya remove
setReconnector(callable $reconnector)
err($message, array $context=array())
hasManyThrough($related, $through, $firstKey=null, $secondKey=null)
setDefault($name, $default)
static addGlobalScope(ScopeInterface $scope)
composers(array $composers)
controllers(array $controllers)
buildFindCommand(Command $command, $dir)
patternsByMethod($method, $filters)
duplicate(array $query=null, array $request=null, array $attributes=null, array $cookies=null, array $files=null, array $server=null)
__construct($staticPrefix, $regex, array $tokens, array $pathVariables, $hostRegex=null, array $hostTokens=array(), array $hostVariables=array(), array $variables=array())
listen($events, $listener, $priority=0)
renderEach($view, $data, $iterator, $empty= 'raw|')
dispatchToQueue($command)
action($action, $parameters=array(), $absolute=true)
transform($messages, $format, $messageKey)
static enableHttpMethodParameterOverride()
setTouchedRelations(array $touches)
registerRequestRebindHandler()
useStoragePathForOptimizations($value=true)
static setInstance(ContainerContract $container)
cloneArgumentsForQueueing(array $arguments)
check($value, $hashedValue, array $options=array())
diffInWeekendDays(Carbon $dt=null, $abs=true)
static updateOrCreate(array $attributes, array $values=array())
trait RouteDependencyResolverTrait
static addVCSPattern($pattern)
addEmergency($message, array $context=array())
assignAfter($instance, $route, $request, $method)
__construct($content= '', $status=200, $headers=array())
registerResponseFactory()
setProtocolVersion($version)
substituteBindings($route)
dispatchToRoute(Request $request)
static parse($time=null, $tz=null)
until($event, $payload=array())
setupWildcardListen($event, $listener)
setEventDispatcher(Dispatcher $dispatcher)
extend($driver, Closure $callback)
static only($array, $keys)
prepareResponse($request, $response)
prepareForUnserialize($data)
customDispatcherIsBound()
static setTrustedHeaderName($key, $value)
belongsToMany($related, $table=null, $foreignKey=null, $otherKey=null, $relation=null)
__construct(\Iterator $iterator, array $matchPatterns, array $noMatchPatterns)
__construct($debug=true, $charset=null, $fileLinkFormat=null)
dropStaleInstances($abstract)
getInt($key, $default=0, $deep=false)
extend($abstract, Closure $closure)
__construct($items=array())
static firstByAttributes($attributes)
forgetAfterFilter($filter)
__construct(Router $router, Container $container=null)
abort($code, $message= '', array $headers=array())
setRootControllerNamespace($rootNamespace)
getWildcardListeners($eventName)
contains($value, $checkForObjectIdentity=true, $checkForNonObjectIdentity=false)
static create($uri, $method= 'GET', $parameters=array(), $cookies=array(), $files=array(), $server=array(), $content=null)
__construct($basePath=null)
checkForAlternateVerbs($request)
__call($method, $parameters)
loadConfigurationFiles(Application $app, RepositoryContract $config)
getMapperSegment($command, $segment)
resolveClass(ReflectionParameter $parameter)
static createFreshMockInstance($name)
compileChoice($expression)
static normalizeQueryString($qs)
forgetInstance($abstract)
static createFromTimestampUTC($timestamp)
setAliases(array $aliases)
getReboundCallbacks($abstract)
static quickRandom($length=16)
getMethodDependencies($callback, $parameters=array())
emergency($message, array $context=array())
newCollection(array $models=array())
getSessionLifetimeInSeconds()
setObservableEvents(array $observables)
dispatch(Route $route, Request $request, $controller, $method)
__construct(Application $app)
static toMonologLevel($level)
replaceRoot($route, $domain, &$parameters)
trait ValidatesWhenResolvedTrait
static createFromGlobals()
static build($array, callable $callback)
setDefaultConnection($name)
getDomainAndScheme($route)
__construct(array $messages=array())
addNotice($message, array $context=array())
lastOfYear($dayOfWeek=null)
getIndexData($data, $prefix)
postReset(Request $request)
getPossibleViewFiles($name)
setEventDispatcher(Dispatcher $events)
addWarning($message, array $context=array())
static setInstance($loader)
bind($abstract, $concrete=null, $shared=false)
callFilter($filter, $route, $request)
dispatchFromArray($command, array $array)
setContainer(Container $container)
static random($length=16)
setExceptionHandler($handler)
setDefaultLogger(LoggerInterface $logger, $levels=null, $replace=false)
function e e window e e e e e e e e dev &&e dispatch e dispatch e e e render e render queue
__construct($app, ConnectionFactory $factory)
stopSection($overwrite=false)
addError($message, array $context=array())
filter(\Closure $closure)
lastOfMonth($dayOfWeek=null)
parseBasicSegments(array $segments)
__construct(HasherContract $hasher, $model)
compileEndfor($expression)
getPlainUri($name, $prefix)
diffInSeconds(Carbon $dt=null, $abs=true)
getRouteDomain($route, &$parameters)
static sort($array, callable $callback)
postLogin(Request $request)
getContent($asResource=false)
addQueryString($uri, array $parameters)
addAlert($message, array $context=array())
setDispatcher(Dispatcher $events)
registerPhpEngine($resolver)
incrementOrDecrement($column, $amount, $method)
static createFromDate($year=null, $month=null, $day=null, $tz=null)
setDefaultLocale($locale)
static hasGlobalScope($scope)
setStatusCode($code, $text=null)
static formatUsesPrefix($new, $old)
registerInstanceFilter($filter)
sendPhpResponse($exception)
__construct(UserProvider $provider, SessionInterface $session, Request $request=null)
then(Closure $destination)
mergeNewFlashes(array $keys)
addFilters($type, $filters)
jl Io Io rc rc rc seconds rc rc rc minutes rc rc rc hours rc month
newPivot(Model $parent, array $attributes, $table, $exists)
static parseParameterFilter($filter)
matches(Route $route, Request $request)
detectEnvironment(Closure $callback)
static where($array, callable $callback)
compileForeach($expression)
registerPresenceVerifier()
addDefaults(array $defaults)
static parseCallback($callback, $default)
setFormat($format= ':message')
parseClassEvent($class, $prefix)
info($message, array $context=array())
performUpdate(Builder $query, array $options=array())
static last($array, callable $callback, $default=null)
ignoreUnreadableDirs($ignore=true)
mutateAttributeForArray($key, $value)
__construct($name, $value=null, $expire=0, $path= '/', $domain=null, $secure=false, $httpOnly=true)
getHandlerClass($command)
replace(array $files=array())
toRoute($route, $parameters, $absolute)
terminate($request, $response)
clearUserDataFromStorage()
static resetToStringFormat()
__construct($name, SessionHandlerInterface $handler, $id=null)
bootstrap(Application $app)
Bo ya ya ya ya ya ya ya ya ya ya ya ya ya ya sort
make($view, $data=array(), $mergeData=array())
getNamespaceSegments($name)
sortListeners($eventName)
filter($key, $default=null, $deep=false, $filter=FILTER_DEFAULT, $options=array())
loadViewsFrom($path, $namespace)
newInstance($attributes=array(), $exists=false)
__construct(Application $app, Router $router)
sortBy($callback, $options=SORT_REGULAR, $descending=false)
compileEndforelse($expression)
__construct($level=Logger::DEBUG, $bubble=true)
static plural($value, $count=2)
sendRequestThroughRouter($request)
static getEventDispatcher()
server($key=null, $default=null)
setRouteResolver(Closure $callback)
attemptBasic(Request $request, $field)
singleton($abstract, $concrete=null)
static slug($title, $separator= '-')
callCustomCreator($driver)
function e e window e e e e e e e e dev &&e dispatch e dispatch e e render
setProvider(UserProvider $provider)
static updated($callback, $priority=0)
trimUrl($root, $path, $tail= '')
getAssignableAfter($filter)
compileAppend($expression)
__construct(EngineResolver $engines, ViewFinderInterface $finder, Dispatcher $events)
static unsetConnectionResolver()
replace(array $attributes)
alert($message, array $context=array())
addEventListener($name, $callback, $priority=null)
callFilter($filter, $request, $response=null)
setParsedKey($key, $parsed)
getContent(FlattenException $exception)
fire($event, $payload=array(), $halt=false)
matches(Route $route, Request $request)
sessionIsPersistent(array $config=null)
static __callStatic($method, $args)
getNumericParameters(array $parameters)
setDefaults(array $defaults)
createReadPdo(array $config)
setRequestFormat($format)
newRoute($methods, $uri, $action)
static safeStrlen($string)
diffInDaysFiltered(Closure $callback, Carbon $dt=null, $abs=true)
static setTestNow(Carbon $testNow=null)
startSection($section, $content= '')
call($callback, array $parameters=array(), $defaultMethod=null)
refresh($abstract, $target, $method)
static flushEventListeners()
static all($columns=array('*'))
matches(Route $route, Request $request)
migrate($destroy=false, $lifetime=null)
setRootControllerNamespace()
compileEmpty($expression)
callPatternFilters($route, $request)
morphToMany($related, $name, $table=null, $foreignKey=null, $otherKey=null, $inverse=false)
bootstrap(Application $app)
critical($message, array $context=array())
callCustomCreator($driver)
mapUsing(Closure $mapper)
bootstrapWith(array $bootstrappers)
to($path, $extra=array(), $secure=null)
__call($method, $parameters)
first(callable $callback=null, $default=null)
render(Closure $callback=null)
__construct(Dispatcher $events, Container $container=null)
static created($callback, $priority=0)
extendSection($section, $content)
forget($name, $path=null, $domain=null)
replaceDefaults(array $parameters)
previous($dayOfWeek=null)
regenerate($destroy=false)
traceAt($levels, $replace=false)
buildContentFiltering(Command $command, array $contains, $not=false)
pull($key, $default=null)
setUser(UserContract $user)
addHidden($attributes=null)
afterFilter($filter, array $options=array())
composer($views, $callback, $priority=null)
useErrorLog($level= 'debug', $messageType=ErrorLogHandler::OPERATING_SYSTEM)
validate(array $credentials=array())
parseClassCallable($listener)
static getFacadeAccessor()
getMiddleware($instance, $method)
nthOfMonth($nth, $dayOfWeek)
wrap(Closure $callback, array $parameters=array())
findCallable(array $action)
getContextualConcrete($abstract)
callRouteFilter($filter, $parameters, $route, $request, $response=null)
detectWebEnvironment(Closure $callback)
file($path, $data=array(), $mergeData=array())
setQueueResolver(callable $resolver)
getAcceptableContentTypes()
__call($method, $parameters)
applyGlobalScopes($builder)
isRedirect($location=null)
static create(array $attributes)
file($key=null, $default=null)
belongsTo($related, $foreignKey=null, $otherKey=null, $relation=null)
input($key=null, $default=null)
registerQueueableEntityResolver()
implode($value, $glue=null)
methodNotAllowed(array $others)
boot(DispatcherContract $events)
static unguard($state=true)
gatherRouteMiddlewares($request)
publishes(array $paths, $group=null)
bootstrap(Application $app)
processRecord(array $record)
prepare(Connection $connection)
isCallableWithAtSign($callback)
nthOfYear($nth, $dayOfWeek)
createQueuedHandlerCallable($class, $method)
__construct(CompilerInterface $compiler)
bootProvider(ServiceProvider $provider)
refreshPdoConnections($name)
callAttachedBefores($route, $request)
pipeThrough(array $pipes)
__construct(array $items=array())
replaceJokers($replacement)
newFromBuilder($attributes=array(), $connection=null)
put($key, MessageBagContract $bag)
__call($method, $parameters)
dispatch(Request $request)
currentRouteUses($action)
getRouteQueryString(array $parameters)
runWithCustomDispatcher(Request $request)
Bo ya ya ya ya ya ya ya ya ya ya data
setFormatter(FormatterInterface $formatter)
addMonthNoOverflow($value=1)
creator($views, $callback)
make(array $config, $name=null)
static parseFilter($filter)
route($method, $name, $routeParameters=[], $parameters=[], $cookies=[], $files=[], $server=[], $content=null)
compileEchoDefaults($value)
detectConsoleEnvironment(Closure $callback, array $args)
search($value, $strict=false)
createSingleConnection(array $config)
getCookieExpirationDate()
getCallbacksForType($abstract, $object, array $callbacksPerType)
mergeReadWriteConfig(array $config, array $merge)
registerBag(SessionBagInterface $bag)
compileOverwrite($expression)
whenRegex($pattern, $name, $methods=null)
parseWhere($name, $expression)
replaceRouteParameters($path, array &$parameters)
handle($request, Closure $next)
buildFindCommand(Command $command, $dir)
diffInMonths(Carbon $dt=null, $abs=true)
setContainer(Container $container)
setParameter($name, $value)
setContentTags($openTag, $closeTag, $escaped=false)
formatDomain($route, &$parameters)
compileStack($expression)
setRequirements(array $requirements)
setAttribute($key, $value)
getReadConfig(array $config)
__construct(Filesystem $files, array $paths, array $extensions=null)
offsetSet($offset, $value)
setVisible(array $visible)
static pull(&$array, $key, $default=null)
static forceCreate(array $attributes)
add(array $files=array())
queued($key, $default=null)
resolvingCallback(Closure $callback)
__construct($methods, $uri, $action)
static getFacadeAccessor()
getCachingIterator($flags=CachingIterator::CALL_TOSTRING)
Bo ya ya ya ya ya ya ya append
setAppends(array $appends)
__call($method, $parameters)
parseNamespacedSegments($key)
loginUsingId($id, $remember=false)
handle(\Exception $exception)
addRoute($methods, $uri, $action)
freshManifest(array $providers)
setNotPath(array $notPaths)
bindParameters(Request $request)
static create($year=null, $month=null, $day=null, $hour=null, $minute=null, $second=null, $tz=null)
hasHintInformation($name)
static setFactory($callable)
handle($request, Closure $next)
where($key, $value, $strict=true)
static parseFilters($filters)
performInsert(Builder $query, array $options=array())
getBasicCredentials(Request $request, $field)
static hasRelativeKeywords($time)
prepare(Request $request)
addNamespace($namespace, $hints)
static resolveConnection($connection=null)
Bo ya ya ya ya ya ya ya ya ya ya ya ya ya ya ya ya ya empty
hasValidCredentials($user, $credentials)
handleBatch(array $records)
setDisplayErrors($displayErrors)
setRoutes(RouteCollection $routes)
getStylesheet(FlattenException $exception)
__construct(EncrypterContract $encrypter)
flash($filter=null, $keys=array())
getFunctionHint(Closure $callback)
pushHandler(HandlerInterface $handler)
callRouteAfter($route, $request, $response)
loadTranslationsFrom($path, $namespace)
warning($message, array $context=array())
static createMockByName($name)
handle($request, Closure $next)
padAndMcrypt($value, $iv)
diffFiltered(CarbonInterval $ci, Closure $callback, Carbon $dt=null, $abs=true)
prependNamespace($namespace, $hints)
__construct(\Iterator $iterator, $mode)
make($name, $value, $minutes=0, $path=null, $domain=null, $secure=false, $httpOnly=true)
jl Io Io rc rc rc seconds rc rc rc minutes rc hour
retrieveItem($source, $key, $default)
notice($message, array $context=array())
addMonthsNoOverflow($value)
bindPathParameters(Request $request)
listen(Closure $callback)
actionReferencesController($action)
__construct($path, array $defaults=array(), array $requirements=array(), array $options=array(), $host= '', $schemes=array(), $methods=array(), $condition= '')